2016-07-10 92 views
0

我需要將函數的輸出重定向到.txt文件。 我使用函數printClassTree()來自庫ontospy。 我的程序的代碼非常簡單:如何使用Linux將我的程序的輸出重定向到.txt文件

import ontospy 
g = ontospy.Graph("/home/gabsbelini/Documentos/ontologiaTeste.owl") 
g.printClassTree() 

我已經試過:

python myprogram.py > file.txt 

但它不工作。 我使用Ubuntu 14.04 當我執行上面的命令,它只是創造了「file.txt的」,並顯示在終端輸出(我想,要保存在file.txt的)

+0

什麼叫 「不工作」 是什麼意思?此外,請參考此答案的一些變化:http://askubuntu.com/questions/420981/how-do-i-save-terminal-output-to-a-file – karthikr

+2

我不知道'g.printClassTree()'是出於某種原因打印到* stderr *而不是* stdout * - 「python myprogram.py 2」file.txt'工作嗎? –

+0

它也可以工作喬恩克萊門茨=)感謝 –

回答

0

嘗試發球:

python myprogram.py | tee file.txt 

或蟒蛇

with open('file.txt', 'w') as fh: 
    fh.write(g.printClassTree()) 

編輯 如果是要stderr你可以嘗試:

python myprogram.py 2> & 1 |三通file.txt的

EDIT2

with open('file.txt', 'w') as fh: 
     fh.write(str(g.printClassTree())) 
+0

感謝您的幫助,但它沒有奏效。 隨着第二個文件被創建,並引發錯誤「Typeerror:預期的字符緩衝區對象」 我GOOGLE了,並被告知在寫入文件之前轉換爲字符串, 更改爲 fh.write(str (g.printClassTree()) 並在文件的輸出是「無」 將嘗試新的建議,非常感謝 –

+0

@gabrielbelini嘗試編輯。 – salparadise

+0

哥們,非常感謝你! 試圖對於很長一段時間! 它的工作!! –

相關問題