2012-02-18 42 views
2

我寫了這個小測試類,基於a Python issue - closed/fixed,它似乎在Python 2.7.1在Fedora 15subprocess.Popen不是線程安全的?

from subprocess import Popen, PIPE 
from threading import Thread 

OUTPUT = "asl;dkfhqwiouethnjzxvnhsldfhuyasdhofuiweqamchuisemfawepfhuaipwemhfuaehfclkuehnflw ehfcoiuwehfiuwmhefuiwehfoiuhSfcl hfulh fuiqhuif huiwafh uiahf iUH fhh flkJH fl HASLFuhSAIULFhSUA HFulSAHfOI SUFChiuwqhncriouweycriuowanbyoUIWCryu iWyruawyrouiWYRcoiu YCRoiuNr uyr oUIAWryocIUWRNyc owuroiuNr cuWyrnawueitcnoy U IuiR yiuowaYnorc oWIUAr coiury iuoAW rnuoi asdfsdfd\n" 


class X(Thread): 
    def __init__(self): 
     Thread.__init__(self) 

    def run(self): 
     print("Running") 
     for i in xrange(10): 
      s = Popen(
       "cat /tmp/junk", 
       shell=True, 
       stdout=PIPE, 
       universal_newlines=True 
      ) 
      output = s.communicate()[0] 
      if not output == OUTPUT: 
       print("Error: %r" % output) 


XThreads = set([]) 

for i in xrange(1000): 
    XThreads.add(X()) 

for x in XThreads: 
    x.start() 

發生只需創建一個文件,在這種情況下的/ tmp /垃圾,有OUTPUT的內容,減去最後一個換行符。

運行這個,你會期望看到每一行「運行」。但是,有時會顯示「正在運行」或「正在運行\ n \ n正在運行」。

(刪除了對實際問題的引用,因爲這是一個假症狀,這要感謝@ phihag的回答)。

的實際問題:https://stackoverflow.com/questions/9338409/python-subprocess-popen-corrupts-binary-streams

回答

2

你看到的行爲無關,與子;我可以重現它:

import threading 
def run(): print("Running") 
for x in [threading.Thread(target=run) for i in range(1000)]: 
    x.start() 

這是因爲Python's print is not thread-safe。爲了避免打印出的文字和換行之間的競爭條件,直接寫入到標準輸出,就像這樣:

import threading,sys 
def run(): sys.stdout.write("Running\n") 
for x in [threading.Thread(target=run) for i in range(1000)]: 
    x.start() 

這是假設的基本write調用到stdout是線程安全的。 That depends on the platform

+0

謝謝,我想我已經找到了我的問題,但需要上傳多個文件以提供一個工作示例 - 不確定如何在此處執行此操作...您能幫忙嗎? – CrackerJack9 2012-02-18 03:35:03

+0

更有趣的是,真正的問題 - http://stackoverflow.com/questions/9338409/python-subprocess-popen-corrupts-binary-streams – CrackerJack9 2012-02-18 04:18:08

+0

@ CrackerJack9通過一些修改,你應該能夠連接任何多文件Python編入一個。如果這是不可能的(或者程序非常長),請將文件上傳到[gist](https://gist.github.com/)或[pastebin](http://pastebin.com) – phihag 2012-02-18 09:50:35

相關問題