2013-01-20 80 views
4

問題1:當sys.stdout.write未包含在單獨的函數中時,下面的代碼失敗。爲什麼我的並行代碼會產生錯誤?

問題2:當ssys.stdout.write被封裝在一個單獨的函數中時,代碼打印每個字母之間的空格。

代碼(V1):

#!/usr/bin/env python 

import pp 
import sys 

def main(): 
    server = pp.Server() 

    for c in "Hello World!\n": 
     server.submit(sys.stdout.write, (c,),(), ("sys",))() 

if __name__=="__main__": 
    main() 

跟蹤:

$ ./parhello.py 
Traceback (most recent call last): 
    File "./parhello.py", line 15, in <module> 
    main() 
    File "./parhello.py", line 12, in main 
    server.submit(write, (c,),(), ("sys",))() 
    File "/Library/Python/2.7/site-packages/pp.py", line 461, in submit 
    sfunc = self.__dumpsfunc((func,) + depfuncs, modules) 
    File "/Library/Python/2.7/site-packages/pp.py", line 639, in __dumpsfunc 
    sources = [self.__get_source(func) for func in funcs] 
    File "/Library/Python/2.7/site-packages/pp.py", line 706, in __get_source 
    sourcelines = inspect.getsourcelines(func)[0] 
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 688, in getsourcelines 
    lines, lnum = findsource(object) 
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 527, in findsource 
    file = getsourcefile(object) 
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 446, in getsourcefile 
    filename = getfile(object) 
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 422, in getfile 
    'function, traceback, frame, or code object'.format(object)) 
TypeError: <built-in method write of file object at 0x1002811e0> is not a module, class, method, function, traceback, frame, or code object 
make: *** [test] Error 1 

代碼(V2):

#!/usr/bin/env python 

import pp 
import sys 

def hello(c): 
    sys.stdout.write(c) 

def main(): 
    server = pp.Server() 

    for c in "Hello World!\n": 
     server.submit(hello, (c,),(), ("sys",))() 

if __name__=="__main__": 
    main() 

跟蹤:

$ ./parhello.py 
H e l l o W o r l d ! 

回答

0

對於第一部分,pp的設計不是爲了處理內置插件而作爲參數submit。第二個問題更復雜。在pp調用提交的函數之前,它將stdout和stderr重定向到一個StringIO對象。上完成任務,它打印從StringIO對象與

print sout, 

的值。這意味着其附加的空間的sout內容打印前。爲了避免這種情況,請勿直接使用sys.stdout,而是將其打印到您管理的文件或隊列中,並以更好的方式處理打印。

相關問題