如何编写一个函数可以启动并杀死python中的子进程?从python函数启动和终止子进程
这是到目前为止我的代码:
import subprocess
import signal
import time
def myfunction(action):
if action == 'start':
print 'Start subrocess'
process = subprocess.Popen("ping google.com", shell=True)
if action == 'stop':
print 'Stop subrocess'
process.send_signal(signal.SIGINT)
myfunction('start')
time.sleep(10)
myfunction('stop')
当我运行这段代码我得到这个错误:
Traceback (most recent call last):
File "test.py", line 15, in <module>
myfunction('stop')
File "test.py", line 11, in myfunction
process.send_signal(signal.SIGINT)
UnboundLocalError: local variable 'process' referenced before assignment
变量过程被破坏。 QuickFix是全局变量或OOP。 – Serge
哇!@Serge,不要那么快建议全局变量!特别是在这种情况下,还有很多其他的快速修复方法可以首先进行。 – waterproof