2017-04-14 64 views
0

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

變量過程被破壞。 QuickFix是全局變量或OOP。 – Serge

+0

哇!@Serge,不要那麼快建議全局變量!特別是在這種情況下,還有很多其他的快速修復方法可以首先進行。 – waterproof

回答

0

你需要學習OOP與構造函數和析構函數定義MyClass的。 假設你不需要運行過程中的許多副本,並使其更奇特的,我們可以使用類方法

class MyClass(object): 
    @classmethod 
    def start(self) 
     print 'Start subrocess' 
     self.process = subprocess.Popen("ping google.com", shell=True) 

    @classmethod 
    def stop(self) 
     self.process.send_signal(signal.SIGINT) 

MyClass.start() 
MyClass.stop() 

這並不理想,因爲它允許您創建多個新進程。 在這種情況下,經常使用singleton模式,確保只有一個進程正在運行,但這有點過時。

最小修復(保持myfunction的)是保存過程中的變量:

import subprocess 
import signal 
import time 

def myfunction(action, process=None): 
    if action == 'start': 
     print 'Start subrocess' 
     process = subprocess.Popen("ping google.com", shell=True) 
     return process 
    if action == 'stop': 
     print 'Stop subrocess' 
     process.send_signal(signal.SIGINT) 

process = myfunction('start') 
time.sleep(10) 
myfunction('stop', process) 
1

您需要保存您的子變量,並傳遞給函數。當您撥打myfunction('stop')時,無法從功能範圍process(因此從UnboundLocalError)。

沒有的功能範圍,這應該很好地工作 - 這表明你的問題是與功能範圍,並沒有真正與工藝處理:

print 'Start subrocess' 
process = subprocess.Popen("ping google.com", shell=True) 
time.sleep(10) 
print 'Stop subprocess' 
process.send_signal(signal.SIGINT) 
0

似乎你所遇到的問題是由於這樣的事實那process被聲明爲myfunction內的局部變量,特別是只在'start' if語句中。這個小範圍意味着當你調用myfunction('stop')時,函數沒有'process'變量的概念。

有幾種方法可以解決這個問題,但最直觀的方法是讓myfunction返回process,然後在您想要關閉時返回process。該代碼看起來是這樣的:

import subprocess 
import signal 
import time 


def myfunction(action, process=None): 
    if action == 'start': 
     print 'Start subrocess' 
     process = subprocess.Popen("ping google.com", shell=True) 
     return process  
    if action == 'stop': 
     print 'Stop subrocess' 
     process.send_signal(signal.SIGTERM) 



process = myfunction('start') 
time.sleep(10) 
myfunction('stop', process) 

我剛纔在2.7.13跑這和它的作品一旦執行功能精細

相關問題