简体   繁体   English

在Unix的背景下运行python脚本

[英]Have python script run in background of unix

I have a python script that I want to execute in the background on my unix server. 我有一个python脚本,我想在UNIX服务器上的后台执行。 The catch is that I need the python script to wait for the previous step to finish before moving onto the next task, yet I want my job to continue to run after I exit. 问题是我需要python脚本来等待上一步完成,然后再执行下一个任务,但是我希望我的工作在退出后继续运行。

I think I can set up as follows but would like confirmation: 我想我可以设置如下,但希望确认:

An excerpt of the script looks like this where command 2 is dependent on the output from command 1 since it outputs an edited executable file in same directory. 该脚本的摘录如下所示,其中命令2取决于命令1的输出,因为它在同一目录中输出已编辑的可执行文件。 I would like to point out that commands 1 and 2 do not have the nohup/& included. 我想指出的是,命令1和2没有包含nohup /&。

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

If when I initiate my python script like so: 如果当我像这样启动我的python脚本时:

% nohup python python_script.py &

Will my script run in the background since I explicitly did not put nohup/& in my scripted unix commands but instead ran the python script in the background? 我的脚本会在后台运行,因为我没有明确将nohup /&放在脚本化的Unix命令中,而是在后台运行了python脚本?

yes, by running your python script with nohup (no hangup), your script won't keel over when the network is severed and the trailing & symbol will run your script in the background. 是的,通过使用nohup(不挂机)运行python脚本,当网络断开时,脚本不会发生扭曲,尾随&符号将在后台运行脚本。

You can still view the output of your script, nohup will pipe the stdout to the nohop.out file. 您仍然可以查看脚本的输出,nohup会将stdout传递给nohop.out文件。 You can babysit the output in real time by tailing that output file: 您可以通过尾随该输出文件来实时查看输出:

$ tail -f nohop.out

quick note about the nohup.out file... 关于nohup.out文件的快速说明...

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

or append the command with & to run the python script as a deamon and tail the logs. 或在命令后加上来作为守护程序运行python脚本并尾随日志。

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

You can use nohup 你可以使用nohup

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

Or 要么

Instead of closing your terminal, use logout It is not SIGHUP when you do logout thus the shell won't send a SIGHUP to any of its children.children. 而不是关闭你的终端,使用logout它时,你是不是SIGHUP logout因此外壳不会发送SIGHUP到任何children.children的。

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

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