python auto restarting script
I need script whi开发者_StackOverflow社区ch starts itself at the end of process. I use this code but it wait for 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 e.g. Linux and Mac, and also on Windows) may be what you want. 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 e.g. -u
for unbuffered std I/O).
To execute a program asynchronously from Python, you can use the Popen function as shown here:
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). 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):
* * * * * /usr/bin/python2.7 script_to_execute.py >/dev/null 2>&1
The line above will run "script_to_execute.py" every minute. You can see some of the examples on the cron Wikipedia page for specifying different intervals at which a script should run.
精彩评论