Reputation: 1234
I'm running python 2.7.3 and doing some basic stuff involving the os module.
import os
def main():
f= os.popen('cat > out', 'w',1)
os.write(f, 'hello pipe')
os.close(f)
main()
Based on examples I've seen I would expect the code to work, but the interpreter gives this error:
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
Okay, off to the documentation. The help page says:
write(...)
write(fd, string) -> byteswritten
Write a string to a file descriptor.
fd seems to stand for file descriptor. Presumably this is what you get when you do something like:
file = open('test.py')
No surprise, online documentation says the exact same thing. What's going on here?
Upvotes: 1
Views: 951
Reputation: 229521
No, a "file descriptor" is an integer, not the file
object. To go from a file
object to a file descroptor, call file.fileno()
. To wit:
>>> 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
Instead of using that, though, you probably just want to do the following, unless you really need to use the low-level functions for some reason:
f = os.popen('cat > out', 'w',1)
f.write('hello pipe')
f.close()
Upvotes: 7