bash 如何在脚本仍在运行时使 shell 输出重定向 (>) 写入?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2753350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make shell output redirect (>) write while script is still running?
提问by noio
I wrote a short script that never terminates. This script continuously generates output that I have to check on every now and then. I'm running it on a lab computer through SSH, and redirecting the output to a file in my public_html folder on that machine.
我写了一个永远不会终止的简短脚本。该脚本不断生成输出,我必须不时检查这些输出。我通过 SSH 在实验室计算机上运行它,并将输出重定向到该计算机上 public_html 文件夹中的文件。
python script.py > ~/public_html/results.txt
However, the results don't show up immediately when I refresh the address. The results show up when I terminate the program, but as I said, it doesn't halt by itself. Is that redirect (>) being lazy with with writing? Is there a way to continuously (or with an interval) update the results in the file?
但是,当我刷新地址时,结果不会立即显示。结果在我终止程序时显示,但正如我所说,它不会自行停止。重定向 ( >) 是否懒于写作?有没有办法连续(或间隔)更新文件中的结果?
Or is it the webserver that doesn't update the file while it is still being written?
或者是在文件仍在写入时不更新文件的网络服务器?
回答by nc3b
回答by Jürgen H?tzel
stdoutis buffered, if not connected to terminal.
如果未连接到终端,则标准输出会被缓冲。
You can change this policy to line-buffering via stdbuf
您可以通过stdbuf将此策略更改为行缓冲
stdbuf -oL python script.py > ~/public_html/results.txt
So you don't have to flush in your Python script and keep it IO efficient, if line-buffering is not required.
因此,如果不需要行缓冲,则不必刷新 Python 脚本并保持其 IO 效率。
回答by Jason R. Coombs
I suspect the file is being continuously written, but that the web server is reporting the modified date of the file as the time it was opened, and thus is reporting that no change to the file has occurred and the result is being cached (either at the web server or at the client).
我怀疑文件正在被连续写入,但是 Web 服务器报告文件的修改日期作为文件打开的时间,因此报告文件没有发生任何更改并且结果正在缓存(或者在Web 服务器或客户端)。
I would first try a forced reload (Ctrl+F5 or Ctrl+Shift+R or Shift+<reload_button>) and see if that helps. If it doesn't, then you can try something else.
我会先尝试强制重新加载(Ctrl+F5 或 Ctrl+Shift+R 或 Shift+<reload_button>),看看是否有帮助。如果没有,那么您可以尝试其他方法。
In a separate shell on the server, do
在服务器上的单独 shell 中,执行
tail -f ~/public_html/results.txt
Tail prints out the last n lines of the file (where n defaults to 10), but the -f parameter monitors the file and continues to report output as the file grows. This will at least give you confidence that the file is being written to incrementally.
Tail 打印出文件的最后 n 行(其中 n 默认为 10),但 -f 参数监视文件并随着文件的增长继续报告输出。这至少会让您确信正在增量写入文件。
I hope that helps.
我希望这有帮助。

