I think it has to do with the terminal the process is attached to. I got this error when I run a python process in the background and closed the terminal in which I started it:
$ myprogram.py
Ctrl-Z
exit
The problem was that I started a not daemonized process in a remote server and logged out (closing the terminal session). A solution was to start a screen/tmux session on the remote server and start the process within this session. Then detaching the session+log out keeps the terminal associated with the process. This works at least in the *nix world.
Answer from jmkg on Stack OverflowI think it has to do with the terminal the process is attached to. I got this error when I run a python process in the background and closed the terminal in which I started it:
$ myprogram.py
Ctrl-Z
exit
The problem was that I started a not daemonized process in a remote server and logged out (closing the terminal session). A solution was to start a screen/tmux session on the remote server and start the process within this session. Then detaching the session+log out keeps the terminal associated with the process. This works at least in the *nix world.
I had a very similar problem. I had a program that was launching several other programs using the subprocess module. Those subprocesses would then print output to the terminal. What I found was that when I closed the main program, it did not terminate the subprocesses automatically (as I had assumed), rather they kept running. So if I terminated both the main program and then the terminal it had been launched from*, the subprocesses no longer had a terminal attached to their stdout, and would throw an IOError. Hope this helps you.
*NB: it must be done in this order. If you just kill the terminal, (for some reason) that would kill both the main program and the subprocesses.
The Exception has an errno attribute:
try:
fp = open("nothere")
except IOError as e:
print(e.errno)
print(e)
Here's how you can do it. Also see the errno module and os.strerror function for some utilities.
import os, errno
try:
f = open('asdfasdf', 'r')
except IOError as ioex:
print 'errno:', ioex.errno
print 'err code:', errno.errorcode[ioex.errno]
print 'err message:', os.strerror(ioex.errno)
- http://docs.python.org/library/errno.html
- http://docs.python.org/library/os.html
For more information on IOError attributes, see the base class EnvironmentError:
- http://docs.python.org/library/exceptions.html?highlight=ioerror#exceptions.EnvironmentError
This is a Windows bug that was fixed with Windows 10 Version 1803. (see https://bugs.python.org/issue32245 and https://github.com/Microsoft/vscode/issues/36630#issuecomment-385759625 )
It affects Python 3.6+ when using code paths that call WriteFile, i.e. os.write and legacy standard I/O mode, and also always affects Python 2.7 and Python 3.5.
Another answer:
I also met same problem in Python 2.7.18 (v2.7.18:8d21aa21f2, Apr 20 2020, 13:25:05) [MSC v.1500 64 bit (AMD64)]
I ran into this issue When I want to process some text which contains Chinese Character.
the core code is:
content = fp.read().strip().strip("\n").split("\n") # fp is an opened file obj
line = "".join([content[x] for x in [1, 4, 7, 10, 13, 16]])
print(line)
the right way is: using unicode instead of str(utf-8) before iter it
content = fp.read().strip().strip("\n").decode("utf-8").split("\n") # fp is an opened file obj
line = "".join([content[x] for x in [1, 4, 7, 10, 13, 16]])
print(line)
You can't print because sys.stdout is not available when not running as a console session.
Instead of using print statements you can consider using the logging module so you can set the loglevel and write all critical things to the system event log.
It should be noted that you can still get it to work (or silently ignore the problem) by doing something like this:
To write to a file per output stream:
import sys
sys.stdout = open('stdout.txt', 'w')
sys.stderr = open('stderr.txt', 'w')
To write to a single file:
import sys
sys.stdout = sys.stderr = open('output.txt', 'w')
Or to silently ignore all print statements:
import sys
class NullWriter(object):
def write(self, value): pass
sys.stdout = sys.stderr = NullWriter()
In Python 2.x, this is the expected behavior. In this bug report, Christian Heimes explains that it is a design decision:
I recommend against changing the code so late in the Python 2.7 release cycle. A change in behavior is too confusing. And it's not a bug but a design decision, too. Over five years ago I implement parts of the IO interaction with the operating system for Python 3.0. I deliberately did NOT port modifications to 2.6.
He also recommends a workaround for obtaining Python 3.x-style print() behavior in Python 2.7:
from __future__ import print_function
import sys
if sys.executable.endswith("pythonw.exe"):
sys.stdout = sys.stdout = None
print("can handle sys.stdout = None just fine.")
os.path.isfile() takes a file path (a string), not a file descriptor (a number), so your solution will not work as you expect.
You can use os.isatty() instead:
if os.isatty(1):
print "text"
os.isatty() will return True if its argument is an open file descriptor connected to a terminal.
(In passing, note that stdout is file descriptor 1. stderr is file descriptor 2).
The above answer did not work for me. But perhaps this is a bug in Python 2.x:
https://bugs.python.org/issue706263
I am using 2.7. os.isatty(1) returns true always but print still raises an exception after 4k bytes. I am using pythonw.exe to run a script in the background.