简体   繁体   English

python自动重启脚本

[英]python auto restarting script

I need script which starts itself at the end of process. 我需要在过程结束时启动的脚本。 I use this code but it wait for execfile. 我使用此代码,但它等待execfile。 How to run it async? 如何异步运行? To do the effect of script restarting. 做脚本重启的效果。

import time
print "start"
time.sleep(5)
print "go exec"
execfile('res.py')
print "stop exec"

One of the many os.exec... functions (on Unix-y systems, including eg Linux and Mac, and also on Windows) may be what you want. 您可能想要许多os.exec ...函数之一(在Unix-y系统上,例如Linux和Mac,以及Windows上)。 You'll need to execute the sys.executable (that's the .exe -- or equivalent executable file on non-Windows OSs -- with the Python version currently in use) with (roughly) the same arguments as are listed in sys.argv (though there may be a bit more work if you also need to reproduce some Python command-line flags, such as eg -u for unbuffered std I/O). 您需要使用(大致)与sys.argv中列出的相同参数来执行sys.executable (即.exe或非Windows操作系统上的等效可执行文件-当前正在使用Python版本)。 (尽管如果您还需要重现一些Python命令行标志,例如可能需要做更多工作,例如-u用于未缓冲的std I / O)。

To execute a program asynchronously from Python, you can use the Popen function as shown here : 若要从Python的异步执行一个程序,你可以使用POPEN功能显示在这里

import subprocess
# ...
pid = subprocess.Popen(["/usr/bin/python2.7", "res.py"]).pid

That said, if you are invoking something over and over again, you probably want to use cron (all UNIX variants, including Linux and Mac OS X) or launchd (Mac OS X). 就是说,如果您要一遍又一遍地调用某些东西,则可能要使用cron (所有UNIX变体,包括Linux和Mac OS X)或已启动 (Mac OS X)。 You can create a cron job by invoking the command crontab -e and then adding a line such as the following (the asterisks below mean "each" and correspond to minutes, hours, days of the month, months, and days of the week): 您可以通过调用命令crontab -e然后添加如下一行来创建cron作业(下面的星号表示“每个”,分别代表分钟,小时,一个月中的某几天,几个月和一周中的几天) :

*    *    *    *    *    /usr/bin/python2.7  script_to_execute.py >/dev/null 2>&1

The line above will run "script_to_execute.py" every minute. 上面的行将每分钟运行“ script_to_execute.py”。 You can see some of the examples on the cron Wikipedia page for specifying different intervals at which a script should run. 您可以在cron Wikipedia页面上看到一些示例,这些示例用于指定脚本运行的不同间隔。

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

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