Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What can lead to "IOError: [Errno 9] Bad file descriptor" during os.system()?

I am using a scientific software including a Python script that is calling os.system() which is used to run another scientific program. While the subprocess is running, Python at some point prints the following:

close failed in file object destructor: IOError: [Errno 9] Bad file descriptor 

I believe that this message is printed at the same time as os.system() returns.

My questions now are:

Which conditions can lead to this type of IOError? What does it exactly mean? What does it mean for the subprocess that has been invoked by os.system()?

like image 381
Dr. Jan-Philip Gehrcke Avatar asked Oct 07 '11 10:10

Dr. Jan-Philip Gehrcke


People also ask

What causes bad file descriptor?

Bad file descriptor; for example, I/O on a descriptor that has been closed or reading from a descriptor open only for writing (or vice versa). There are no child processes. This error happens on operations that are supposed to manipulate child processes, when there aren't any processes to manipulate.

What is bad file descriptor error in Python?

Understanding [Errno 9] Bad File Descriptor Error in PythonWhen you don't allow the code to perform the functions related to the file descriptors and the methods used, these kinds of issues arise, indicating the wrong way of implementing the code.


2 Answers

You get this error message if a Python file was closed from "the outside", i.e. not from the file object's close() method:

>>> f = open(".bashrc") >>> os.close(f.fileno()) >>> del f close failed in file object destructor: IOError: [Errno 9] Bad file descriptor 

The line del f deletes the last reference to the file object, causing its destructor file.__del__ to be called. The internal state of the file object indicates the file is still open since f.close() was never called, so the destructor tries to close the file. The OS subsequently throws an error because of the attempt to close a file that's not open.

Since the implementation of os.system() does not create any Python file objects, it does not seem likely that the system() call is the origin of the error. Maybe you could show a bit more code?

like image 156
Sven Marnach Avatar answered Oct 12 '22 16:10

Sven Marnach


You can get this error if you use wrong mode when opening the file. For example:

    with open(output, 'wb') as output_file:         print output_file.read() 

In that code, I want to read the file, but I use mode wb instead of r or r+

like image 21
Aminah Nuraini Avatar answered Oct 12 '22 16:10

Aminah Nuraini