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

17.7K    Asked by MayankMistry in Tableau , Asked on Jun 7, 2021

I'm using os.system(), which is a scientific software including a python script, used to run another scientific program. There's a subprocess, which will be running and python will print the following:

close failed in file object destructor:
IOError: [Errno 9] Bad file descriptor
Even this message will be printed at the same time as os.system()?

But my question is, Which condition will lead to this type of IOError? What is it? 

Answered by Ayushi Khatri

You get this kind of error “oserror: [errno 9] bad file descriptor” message only if python file was closed from the outside, i.e.,not from the file objects close() :

>>> f = open(".bashrc")

>>> os.close(f.fileno())

>>> del f

close failed in file object destructor:

IOError: [Errno 9] Bad file descriptor

In the above code, del f line will delete the last reference to the file object, Ultimately file.__del__ will be called.

The Internal state indicates that the file is still open since f.close() was never called, So here someone tries to close the file, that someone is a destructor here. Later, OS throws an error because of the attempt for closing the file, which is not open.

Since os.system() does not create any python file object, It doesn't look like system() call was the origin of the error

Reason for getting error “oserror: [errno 9] bad file descriptor” :

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.



Your Answer

Interviews

Parent Categories