Say i want to do
import subprocess
subprocess.call(["foo"])
My question is, how could i run subprocess.call(["foo"]) every x seconds, then kill the process, then repeat x seconds later?
Say i want to do
import subprocess
subprocess.call(["foo"])
My question is, how could i run subprocess.call(["foo"]) every x seconds, then kill the process, then repeat x seconds later?
To run a command every x seconds you can use a infinite loop and time
import os
import signal
import subprocess
import time
cmd = "python -m SimpleHTTPServer"
while True:
server = subprocess.Popen(cmd , stdout=subprocess.PIPE, shell=True,
preexec_fn=os.setsid)
time.sleep(10)
os.killpg(os.getpgid(server.pid), signal.SIGTERM)
time.sleep(5)
If you don't know how to stop the process I recommend you to check https://stackoverflow.com/a/4791612/2588566
If you just want the process to run x time sleeping use a for
loop instead.
I don't know what command you want to run. In this example you run a python server serving files in the current dir. It start the process, keep it running for 10 seconds, then kill the process and waits 5 seconds (So you can check it has been stopped). So you have a server running 10 seconds and a gap of 5 seconds between each execution.
subprocess.call
does not return until the process foo
finishes.
Run the command described by args. Wait for command to complete, then return the returncode attribute.
Use Popen
instead.
import subprocess
import time
while True:
# The process will take 10 seconds to finish, but ...
p = subprocess.Popen(["sleep", "10"])
# ... we kill it after 5 seconds.
time.sleep(5)
p.kill()
There is a system of instructions can be done. Code does not need to set the cycle, starting from the main function, the implementation of the output and rest, and then restart the process
import time
import sys
import os
def restart_program():
python = sys.executable
os.execl(python, python, * sys.argv)
if __name__ == "__main__":
print 'start...'
print "sleep 3s..."
time.sleep(3)
restart_program()