![](/img/trans.png)
[英]How to open multiple terminals and execute command in each terminal then save the output from each terminal to a one variable or a file
[英]Save command output to file and see it on the terminal
我有一個緩慢輸出列表的命令。 我希望將此列表保存在文件中,並且還希望它在終端上緩慢生成。
python script.py 2>&1 | tee File.txt
這對我不起作用。 保存命令后,在終端上看不到網站列表。
默認情況下,stdout在進入終端時是行緩沖的,但是在重定向時使用更大的緩沖區,因此tee和終端直到稍后才看到輸出。
有關使script.py不緩沖輸出的方法,請參見此問題的答案禁用輸出緩沖
例如,如果script.py是:
#!/usr/bin/python3
import time
for i in range(5):
print('This is line', i, flush=True)
time.sleep(1)
運行./script.py | tee File.txt
./script.py | tee File.txt
將在執行每一行時將每一行打印到終端(相隔一秒)。
如果刪除flush=True
則整個輸出都將被緩沖,並且在打印所有內容后5秒后腳本完成之前,不會打印任何內容。
2>&1
將stderr重定向到stdout,因此您可能需要對stderr和stdout應用相同的緩沖。
根據Linux文檔項目(TLDP) ,
2>&1#將stderr重定向到stdout。 #錯誤消息被發送到與標准輸出相同的位置。
和,
&>文件名#將stdout和stderr都重定向到文件“文件名”。
因此,要將兩者通過管道傳輸到文件,
Command &> | tee File.txt
或者只是stdout
,
Command | tee File.txt
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.