"ValueError: I/O operation on closed file" when calling subprocess

"ValueError: I/O operation on closed file" when calling subprocess

我只是想调用 tracert 并以字符串形式获取结果。 tracert 调用似乎工作正常,因为结果在错误发生之前显示在控制台上。

    import subprocess
    import sys
    proc = subprocess.Popen(["tracert", "localhost"], stderr=subprocess.PIPE, stdin=subprocess.PIPE)
    print proc.communicate()[0]

错误:

Traceback (most recent call last):
  File "-", line 207, in <module>
    main()
  File "-", line 203, in main
    tracert("localhost")
  File "-", line 188, in tracert
    print proc.communicate()[1]
ValueError: I/O operation on closed file

更新: 我尝试 logging 而不是 print,因为它是无缓冲的。

2017-09-07 09:11:57,165 - [test] - INFO - 

Routenverfolgung zu localhost [::1]

�ber maximal 30 Hops:



  1    <1 ms    <1 ms    <1 ms  localhost [::1] 



Ablaufverfolgung beendet.


Traceback (most recent call last):
  File "-\lib\logging\__init__.py", line 885, in emit
    self.flush()
  File "-\logging\__init__.py", line 845, in flush
    self.stream.flush()
ValueError: I/O operation on closed file

不知何故 stdout 已关闭,我无法写入流。 所以这个问题与 subprocess 完全无关。