2017-04-14 66 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跑这和它的作品一旦执行功能精细

相关问题