2013-09-01 43 views
0

我正在運行python 2.7.3並執行一些涉及os模塊的基本工作。基於我見過我希望工作代碼示例Python os.popen需要一個整數?

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 

好了,關閉的文檔。幫助頁面上說:

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

    Write a string to a file descriptor. 

fd似乎代表文件描述符。想必這是你做什麼時,你會得到:

file = open('test.py') 

毫不奇怪,在線文檔說,完全一樣的東西。 這是怎麼回事?

+1

使用'subprocess'? –

+0

因爲我想從網站獲取數據,並且隨着數據傳入另一個進程。有沒有更好的方法來做到這一點與子進程? – Muricula

回答

6

不,「文件描述符」是一個整數,而不是file對象。要從file對象轉到文件掃描器,請致電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 

而不是使用,不過,你可能只是想做到以下幾點,除非你真的需要使用低級別的功能,出於某種原因的:爲什麼不乾脆

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

所以它工作,但爲什麼python使用一個整數作爲文件描述符?爲什麼不只是文件對象?文件描述符是某種指針嗎? – Muricula

+1

@Muricula:文件描述符將與低級C庫進行接口。這是他們用來做文件I/O的。 python很好地包裝了這個文件對象,但是如果你使用低級庫,那麼你必須給他們他們知道的東西 – Claudiu