
我是 Linux 的新使用者。我編寫了一個帶有循環的 Python 程序,該循環運行 10 次並每次打印一行。我將其儲存為 Printing.py 現在我想使用終端機來確保列印輸出保存在新檔案中。
我使用的程式碼是:
counter = 1
while counter <= 10:
print("This is line", counter)
counter = counter +1
但是,我不知道如何從透過終端另存為 print.py 的程式取得新檔案「結果」。
答案1
您可以使用 > 運算子重定向程式的輸出。然後輸出被寫入給定檔案而不是終端:
python3 printing.py > result
請注意,文字不會附加,而是取代文件的當前內容。如果要將輸出附加到文件,請使用 >> 運算子。
還有一種方法可以在終端機上取得輸出和在文件中,這樣您就可以看到發生了什麼。只需將輸出通過管道傳輸到命令即可球座它會將其列印到您的終端和文件中。您可以將此命令想像為一個 T 形管道,它將其輸入重定向到兩個輸出。
python3 printing.py | tee result
這將再次覆蓋文件的當前內容。
答案2
將以下內容複製並貼上到檔案 test.py 中
#!/usr/bin/env python3
#
counter = 1
while counter <= 10:
print("This is line", counter)
counter = counter + 1
現在運行命令
chmod +x test.py
./test.py > output.txt
輸出應該是
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8
This is line 9
This is line 10