0

I already searched several solutions on this site, but unfortunately the provided ones didn't work out for me.

Let's say I have a python script called "DataGen.py" that stops running (green arrow is clickable) because some background program is crashing. Unfortunately, there is no exception being thrown, which is why I need a workaround:

What I'm searching for is another python script called "RestartScript.py" that restarts "DataGen.py" 60 seconds after it has stopped running.

I tried something like:

from os import system
from time import sleep

while True:
    system('DataGen.py')
    sleep(300)
Dorian IL
  • 199
  • 2
  • 11
  • 2
    Have you tried `os.system("python DataGen.py")`? – Alex Yu Feb 14 '19 at 14:48
  • 1
    This might help you to identify whether your script is currently running or not: https://stackoverflow.com/questions/788411/check-to-see-if-python-script-is-running – DocDriven Feb 14 '19 at 14:49
  • @AlexYu this seems to work. What does the sleep command do in this context? – Dorian IL Feb 14 '19 at 14:52
  • It [suspend execution of the calling thread for the given number of seconds](https://docs.python.org/3.7/library/time.html#time.sleep) – Alex Yu Feb 14 '19 at 14:56

1 Answers1

3

The system function executes what command you use as input.. See link. As such, this would be how you would run it to achieve the results you desire:

system('python DataGen.py')

Also, whatever value used as input in the sleep function is supposed to be seconds.. Using this logic, your code reruns every 300 seconds.

See below for full solution:

from os import system
from time import sleep

while True:
    system('python DataGen.py')
    sleep(60)
prismo
  • 1,505
  • 2
  • 12
  • 26
  • 2
    It's a good start, but if you want to monitor `DataGen.py` from a master process, `subprocess.call` or the likes would probably be a better choice. Besides, there is no `restart if crashed` logic, which I would find much more interesting. I think a satisfying solution would be to pass `DataGen.py`'s pid to a `monitor` function, that would regularly check if the process is still running, and restart it if it crashed. Maybe `os.system('ps')` then a lookup for this pid would be a good starter. – Right leg Feb 14 '19 at 14:58
  • @Rightleg This would also be better for my purposes. The link "DocDriven" posted under the question is what you're refering to I think. – Dorian IL Feb 14 '19 at 15:03