【问题标题】:Have python script run in background of unix让python脚本在unix后台运行
【发布时间】:2017-07-09 06:11:20
【问题描述】:

我有一个 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 &

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

【问题讨论】:

    标签: python unix subprocess nohup


    【解决方案1】:

    是的,通过使用 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
    

    【讨论】:

    • 谢谢 - nohup.out 文件是默认创建的吗?在后台启动程序后列出目录项时,我从未看到此文件。
    【解决方案2】:

    您可以使用nohup

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

    或者

    不要关闭终端,而是使用logout 当你使用logout 时它不是 SIGHUP,因此 shell 不会向它的任何 children.children 发送 SIGHUP。

    【讨论】:

      猜你喜欢
      • 2021-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 2017-11-21
      相关资源
      最近更新 更多