简体   繁体   English

在服务器后台运行 python 脚本并获取脚本 output

[英]Run python script in background on server and get script output

So, I need to run a python script on a server but I want the script to output whatever it outputs into a file so I can check what it done after it finished.所以,我需要在服务器上运行 python 脚本,但我希望脚本到 output 输出到文件中,以便我可以检查它在完成后做了什么。 However I also need the script to continue running if the ssh tunnel to the server gets interrupted or closed.但是,如果到服务器的 ssh 隧道中断或关闭,我还需要脚本继续运行。 Here is what I know:这是我所知道的:

python3 run.py >> out.txt
will output correctly.将 output 正确。

nohup python3 run.py
will output correctly and be safe from interruption.将 output 正确并避免中断。 it will also output into a nohup.out but will not run in the background of the current session (thus blocking me from doing anything else).它还将 output 进入 nohup.out 但不会在当前 session 的后台运行(从而阻止我做任何其他事情)。

So I would think所以我会认为

nohup python3 run.py >> out.txt &
would work for me but it does not.会为我工作,但它没有。
I've tried different combinations of what I want but just cannot get it to work... once I add & it appears the output to the files just stops going.我已经尝试了我想要的不同组合,但无法让它工作......一旦我添加&它似乎 output 文件就停止了。 I have no clue why though.我不知道为什么。 any help appreciated!任何帮助表示赞赏!

What you are looking for is been already answered here您正在寻找的内容已经在这里得到解答

https://askubuntu.com/questions/8653/how-to-keep-processes-running-after-ending-ssh-session https://askubuntu.com/questions/8653/how-to-keep-processes-running-after-ending-ssh-session

You need to use tmux to keep it running in background您需要使用tmux使其在后台运行

The easiest way is to run your command in the background with & .最简单的方法是使用&在后台运行您的命令。 Then just write:然后只写:

disown -a

for anyone experiencing similar issues there is problem with nohup and python output buffering I guess.对于遇到类似问题的任何人,我猜 nohup 和 python output 缓冲存在问题。
see: Nohup is not writing log to output file .请参阅: Nohup 未将日志写入 output 文件

but the fix is:但解决方法是:

nohup python3 -u run.py >> out.txt &

(Answer provided by @VPfB) (@VPfB 提供的答案)

Just look here :看看这里

python3 yourscript.py >> out.txt & disown

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM