Python: subprocess.communication(): ValueError with print() 函数,但不内置"print"



我正在尝试从Python使用子进程模块运行C程序,并在变量中捕获其输出。代码看起来像这样:

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

上述代码作品-result显示为myprog的Stdout输出和STDERR输出(作为字符串)的2件托盘。

... 但是,如果我将print result更改为print(result) ...

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

我在这里完全被困在这里,我什至不知道从哪里开始尝试解释这一点!当然,我的程序无论如何都可以工作,但是我真的很想知道为什么会发生这种情况,希望这将是一个有趣的问题。

这是不是一个问题。您对myprog而不是Python有问题。

在Python 2中,print somethingprint(something)之间的差异为无效和无效。 no 完全差异是因为Python编译器将括号视为NO-OP,并且所得的字节代码完全相同:

>>> 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        

最新更新