在 unix 后台有 python 脚本 运行

Have python script run in background of unix

我有一个 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 脚本?

是的,通过 运行将您的 python 脚本与 nohup(无挂断)连接起来,当网络被切断时您的脚本将不会崩溃并且尾随 & 符号将 运行 你的脚本在后台。

您仍然可以查看脚本的输出,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

您可以使用nohup

  1. chomd +x /path/to/script.py
  2. nohup python /path/to/script.py &

不用关闭你的终端,而是使用 logout 当你这样做时它不是 SIGHUP logout 因此 shell 不会向它的任何 children.children.