在os.system()期间会导致"IOError:[Errno 9]错误文件描述符"的原因是什么?

Jan*_*cke 52 python posix subprocess file-descriptor ioerror

我正在使用一个科学软件,包括一个os.system()用于运行另一个科学程序的Python脚本.在子进程运行时,Python在某些时候打印以下内容:

close failed in file object destructor:
IOError: [Errno 9] Bad file descriptor
Run Code Online (Sandbox Code Playgroud)

我相信此消息会在os.system()返回的同时打印出来.

我现在的问题是:

哪种情况会导致这种类型的IOError?它究竟意味着什么?对于已被调用的子进程意味着什么os.system()

Sve*_*ach 47

如果从"外部"关闭Python文件,即从文件对象的close()方法中关闭,则会收到此错误消息:

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

该行del f删除对文件对象的最后一个引用,导致其析构函数file.__del__被调用.文件对象的内部状态表明文件仍然处于打开状态,因为f.close()从未调用过,因此析构函数会尝试关闭该文件.操作系统随后因为尝试关闭未打开的文件而抛出错误.

由于实现os.system()不会创建任何Python文件对象,因此system()调用似乎不太可能是错误的起源.也许你可以展示更多的代码?

  • @ Jan-PhilipGehrcke:如果你使用的是Python 2.6或2.7,你可以尝试一下hack:`import io; __builtins__.open = io.open`用`io`模块中的版本替换了`open()`builtin(从3.0后面移植).新版本的`open()`速度较慢,但​​如果文件已经关闭则忽略. (2认同)

Ami*_*ini 15

如果在打开文件时使用错误模式,则会出现此错误.例如:

    with open(output, 'wb') as output_file:
        print output_file.read()
Run Code Online (Sandbox Code Playgroud)

在那段代码中,我想读取文件,但我使用的是mode wb而不是rorr+