2016-07-26 39 views
0

我在Python服务器脚本中运行两个子进程。子流程的目的是从我的Raspberry Pi流式传输视频。如何用其他命令杀死子进程python

我的问题是如何杀死子进程时,另一个命令发送到服务器。我正在使用Popen()来启动子进程。

这是我的代码,当服务器收到命令“startStream”。我使用Twisted库作为服务器协议。

class Echo(Protocol): 
    def connectionMade(self): 
     #self.transport.write("""connected""") 
     self.factory.clients.append(self) 
     print "clients are ", self.factory.clients 

    def connectionLost(self, reason): 
     self.factory.clients.remove(self) 

    def dataReceived(self, data): 
     print "data is ", data 

     if data == "startStream": 
      p = subprocess.Popen("raspistill --nopreview -w 640 -h 480 -q 5 -o /tmp/stream/pic.jpg -tl 100 -t 9999999 -th 0:0:0 &", shell=True) 
      pn = subprocess.Popen("LD_LIBRARY_PATH=/usr/local/lib mjpg_streamer -i %s -o %s &" % (x,y), shell=True) 

我想要的是这样的。

if data == "startStream": 
     p = subprocess.Popen("raspistill --nopreview -w 640 -h 480 -q 5 -o /tmp/stream/pic.jpg -tl 100 -t 9999999 -th 0:0:0 &", shell=True) 
     pn = subprocess.Popen("LD_LIBRARY_PATH=/usr/local/lib mjpg_streamer -i %s -o %s &" % (x,y), shell=True) 
elif data == "stopStream": 
     os.kill(p.pid) 
     os.kill(pn.pid) 

非常感谢!

+1

'terminate()'? – BusyAnt

+0

问题是当调用stopStream时,p和pn不可访问。我习惯于使用Java,在那里我可以刚刚声明过程为全局变量,然后从任何地方访问它们,但显然这在Python中不起作用。 – Oliver

+0

此外,该模块没有任何属性终止 – Oliver

回答

1

你在这里失去了一些背景,但基本上像服务器会做一些事情:

while True: 
    data = wait_for_request() 
    if data == 'startStream': 
     p = subprocess.Popen("raspistill --nopreview -w 640 -h 480 -q 5 -o /tmp/stream/pic.jpg -tl 100 -t 9999999 -th 0:0:0 &", shell=True) 
     pn = subprocess.Popen("LD_LIBRARY_PATH=/usr/local/lib mjpg_streamer -i %s -o %s &" % (x,y), shell=True) 
    elif data == 'stopStream': 
     p.terminate() 
     pn.terminate() 

的关键部分是名ppn存在于相同的范围,因此他们没有使用任何类型的访问全球状态。如果你的代码结构不同,你需要概述它的问题。

由于data_received在每次调用中都有自己的作用域,所以您需要以不同的方式传递对您的Popen对象的引用。 幸运的是,您可以在类实例中保留引用。

def dataReceived(self, data): 
    if data=='startStream': 
     self.p = subprocess.Popen() # ... 
     self.pn = subprocess.Popen() # ... 
    elif data=='stopStream': 
     self.p.terminate() 
     self.pn.terminate() 

Popen.terminate可在Python 2.6和应该工作得很好 - 我不知道什么是有问题的意见的问题。

+0

请参阅我更新的代码。这就是我的服务器代码当前的样子。 – Oliver

+0

也如上所述terminate()不起作用。 – Oliver

+0

我无法让它工作。传递给我的Popen对象的引用是什么意思? – Oliver