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

Python os.popen需要一个整数吗?,python,Python,我正在运行Python2.7.3,并做一些涉及操作系统模块的基本工作 import os def main(): f= os.popen('cat > out', 'w',1) os.write(f, 'hello pipe') os.close(f) main() 根据我看到的示例,我希望代码能够正常工作,但解释器给出了以下错误: Traceback (most recent call last): File "./test.py", line 11,

我正在运行Python2.7.3,并做一些涉及操作系统模块的基本工作

import os

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

main()
根据我看到的示例,我希望代码能够正常工作,但解释器给出了以下错误:

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
fd似乎代表文件描述符。大概这就是你做以下事情时得到的结果:

file = open('test.py')
毫不奇怪,在线文档中也有同样的说法。 这里发生了什么?

不,“文件描述符”是一个整数,而不是
文件
对象。要从
文件
对象转到文件描述符,请调用
文件.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
但是,您可能只想执行以下操作,而不是使用它,除非出于某种原因确实需要使用低级函数:

f = os.popen('cat  > out', 'w',1)
f.write('hello pipe')
f.close()
否,“文件描述符”是一个整数,而不是
文件
对象。要从
文件
对象转到文件描述符,请调用
文件.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
但是,您可能只想执行以下操作,而不是使用它,除非出于某种原因确实需要使用低级函数:

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

为什么不直接使用
子流程
?因为我想从一个网站获取数据,当数据通过管道传输到另一个流程时。有没有更好的方法来处理子流程?为什么不直接使用
subprocess
?因为我想从一个网站获取数据,当数据进入到另一个流程时,通过管道将其传输到另一个流程。有没有更好的方法来处理子流程呢?所以它是有效的,但是为什么python使用整数作为文件描述符呢?为什么不仅仅是文件对象?文件描述符是某种指针吗?@Muricula:文件描述符是用来与低级C库接口的。这是他们用来做文件i/o的。python用file对象很好地包装了这一点,但是如果您使用的是低级库,那么您必须向它们提供它们所知道的东西,所以它是有效的,但是python为什么使用整数作为文件描述符呢?为什么不仅仅是文件对象?文件描述符是某种指针吗?@Muricula:文件描述符是用来与低级C库接口的。这是他们用来做文件i/o的。python用file对象很好地包装了这一点,但是如果您使用的是低级库,那么您必须向它们提供它们所知道的内容