如何編寫一個函數可以啓動並殺死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