Python os.popen需要一个整数吗?

Mur*_*ula 0 python

我正在运行python 2.7.3并做一些涉及os模块的基本内容.

import os

def main():
    f= os.popen('cat  > out', 'w',1)
    os.write(f, 'hello pipe')
    os.close(f)

main()
Run Code Online (Sandbox Code Playgroud)

根据我看到的例子,我希望代码可以工作,但是解释器给出了这个错误:

Traceback (most recent call last):
  File "./test.py", line 11, in <module>
    main()
  File "./test.py", line 8, in main
    os.write(f, 'hello pipe')
TypeError: an integer is required
Run Code Online (Sandbox Code Playgroud)

好的,关闭文档.帮助页面说:

write(...)
    write(fd, string) -> byteswritten

    Write a string to a file descriptor.
Run Code Online (Sandbox Code Playgroud)

fd似乎代表文件描述符.据推测,当你做类似的事情时,这就是你得到的:

file = open('test.py')
Run Code Online (Sandbox Code Playgroud)

毫不奇怪,在线文档说的完全一样.这里发生了什么?

Cla*_*diu 6

不,"文件描述符"是整数,而不是file对象.要从file对象转到文件descroptor,请致电file.fileno().以机智:

>>> f = open("tmp.txt", "w")
>>> help(f.fileno)
Help on built-in function fileno:

fileno(...)
    fileno() -> integer "file descriptor".

    This is needed for lower-level file interfaces, such os.read().

>>> f.fileno()
4
Run Code Online (Sandbox Code Playgroud)

但是,您可能只想执行以下操作,而不是使用它,除非您出于某种原因确实需要使用低级函数:

f = os.popen('cat  > out', 'w',1)
f.write('hello pipe')
f.close()
Run Code Online (Sandbox Code Playgroud)