Search code examples
pythonsubprocessioerror

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


I am just trying to call tracert and get the result as a string. It seems the tracert call is working correctly, because the result is displayed on the console before the error occurs.

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

Error:

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

UPDATE: I tried logging instead of print, because it is unbuffered.

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

Solution

  • Somehow the stdout was closed and I could not write to the stream. So the problem had nothing to do with subprocess at all.