Skip to main content
 首页 » 编程设计

python之让python脚本在unix的后台运行

2025年05月04日16java哥

我有一个 python 脚本,我想在我的 unix 服务器的后台执行。问题是我需要 python 脚本等待上一步完成才能继续下一个任务,但我希望我的工作在退出后继续运行。

我想我可以设置如下,但需要确认:

脚本的摘录如下所示,其中命令 2 依赖于命令 1 的输出,因为它在同一目录中输出编辑后的可执行文件。我想指出命令 1 和 2 没有包含 nohup/&。

subprocess.call('unix command 1 with options', shell=True) 
subprocess.call('unix command 2 with options', shell=True) 

如果当我像这样启动我的 python 脚本时:

% nohup python python_script.py & 

我的脚本是否会在后台运行,因为我明确没有在我的脚本化 unix 命令中放置 nohup/& 而是在后台运行 python 脚本?

请您参考如下方法:

是的,通过使用 nohup(无挂断)运行您的 python 脚本,当网络被切断时您的脚本将不会崩溃,尾随的 & 符号将在后台运行您的脚本。

您仍然可以查看脚本的输出,nohup 会将标准输出通过管道传输到 nohop.out 文件。您可以通过跟踪输出文件来实时照看输出:

$ tail -f nohop.out 

关于 nohup.out 文件的快速说明...

nohup.out          The output file of the nohup execution if 
                   standard  output is a terminal and if the 
                   current directory is writable. 

或在命令后附加 & 以将 python 脚本作为守护进程运行并跟踪日志。

$ nohup python python_script.py > my_output.log & 
$ tail -f my_output.log