2016-07-26 40 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