2012-11-08 42 views
0

我想從Python運行一個C程序與子進程模塊,捕獲其變量輸出。代碼看起來是這樣的:Python:subprocess.communicate():ValueError與打印()函數,但不是「打印」內置

process = Popen(["myprog", str(length), filename], stdout=PIPE, stderr=PIPE) 
#wait for the process 
result = process.communicate() 
end=time() 
print result 

上面的代碼工作 - result被示爲myprog的標準輸出輸出和stderr輸出(字符串)的2元組。

... 然而如果我改變print resultprint(result) ...

Traceback (most recent call last): 
    File "tests.py", line 26, in <module> 
    print(result) 
ValueError: I/O operation on closed file 

我在這裏完全難倒,我甚至不知道從哪裏開始試圖解釋這個!當然,我的程序無論如何都適用,但我真的很想知道爲什麼會發生這種情況,並希望這會是一個有趣的問題。

+0

請你向我們展示了整個Python和整個C程序? – User

回答

4

這是不是一個Python問題。你有一個myprog的問題,而不是Python。

在Python 2中,print somethingprint(something)之間的區別是無效的。有沒有區別,因爲在所有的Python的編譯器看到括號爲空操作,所產生的字節碼是完全一樣的:

>>> import dis 
>>> def foo(): print 'bar' 
... 
>>> dis.dis(foo) 
    1   0 LOAD_CONST    1 ('bar') 
       3 PRINT_ITEM   
       4 PRINT_NEWLINE  
       5 LOAD_CONST    0 (None) 
       8 RETURN_VALUE   
>>> def foo(): print('bar') 
... 
>>> dis.dis(foo) 
    1   0 LOAD_CONST    1 ('bar') 
       3 PRINT_ITEM   
       4 PRINT_NEWLINE  
       5 LOAD_CONST    0 (None) 
       8 RETURN_VALUE