2014-11-05 114 views

回答

-1

我不完全是積極的。我不認爲有一種方法可以讓waitpid或相當於一個完全非侵入性的同步超時。另外,我認爲一些Unices對於waitpid如何使用信號玩法有不同的規則。

評論說他們偷了Thread.wait的循環,threading.py中的註釋表明它用於響應。

1
from subprocess import Popen, PIPE 

handle = Popen('ping -n 100 www.google.se', shell=True, stdout=PIPE) 
while handle.poll() is None: # <-- Equivilant of .wait() 
    print(handle.stdout.readline()) 

等待是.poll(),它基本上沒有,除非你手動使用.poll()在保持循環,您可以在此過程中計算的東西同樣的事情速記功能。

通常它用於轉儲出標準輸出/標準錯誤的東西(如果你不能阻止應用程序或引發異常)。

還使用shell是有風險的,但它在學習和測試時可以節省很多頭痛。

真正不會阻止在所有東西(即使上述方法「塊」下一行中的代碼)的唯一方式是向utelize線程:

from threading import * 
from subprocess import Popen, PIPE 

class worker(Thread): 
    def __init__(self, command): 
     Thread.__init__(self) 
     self.handle = Popen(command, shell=True, stdout=PIPE) 
     self.start() 

    def run(self): 
     while self.handle.poll() is None: 
      print('Thread-output',self.handle.stdout.readline()) # Note, you might loose the last output.. just saying. 

print('I\'m a panda..') 
worker('ping -n 100 www.google.se') 
print('And i work really well simultaneously...') 

有用尖端調試時:

from subprocess import Popen, PIPE, STDOUT 
handle = Popen('ping -n 100 www.google.se', shell=True, stdout=PIPE, stderr=PIPE) 
# You need to flush the output buffers: 
handle.stderr.readline() 
handle.stdout.readline() 
# or 
handle = Popen('ping -n 100 www.google.se', shell=True, stdout=PIPE, stderr=STDOUT) 
handle.stdout.readline() # Does both stdout+stderr at the same time, saves you a line. 

# and always close your open filehandles. 
handle.stdout.close() 
handle.stderr.close() # If you've separated both. 

關於你的操作系統問題

我想你可能指的是系統服務或守護進程?
這些類型的「進程」,你描述他們被指定爲阻塞或非阻塞(這是你正在尋找的術語)。這些進程的每個init腳本的開發者決定進程是否應該被阻塞直到完成(或達到超時)或進程應該分入後臺。

可能被阻止的事情是OpenLDAP或內部郵件傳輸器,而其他進程(例如OpenVPN或Apache)可能會分入後臺,讓系統啓用以繼續它的啓動順序。

+0

不必要地運行一個shell並不能挽救頭痛,它會創建它們(並且更糟!) – 2014-11-05 18:55:50

+0

@MikeGraham如果你不知道去除什麼東西,它確實如此。因爲任何unix shell都可以做到這一點,所以它的行爲會更好。我意識到不使用這是理想的,但對於新的unix用戶來說,像任何其他具有環境變量的unix shell一樣運行的默認行爲更容易。 – Torxed 2014-11-05 20:28:33

+0

@Torxed根據[this](https://stackoverflow.com/questions/26750541/how-does-time-wait-for-a-process-that-it-is-timing),我們可以阻止呼叫而不需要在Unix上忙於循環。那麼爲什麼不在Popen.wait上實現呢,因爲忙於等待進程完成浪費CPU資源? – ggg 2014-11-06 01:00:37