11

I have a python script that will be running that basically collects data and inserts it into a database based on the last time the database was updated. Basically, i want this script to keep running and never stop, and to start up again after it finishes. What would be the best way to do this?

I considered using a cronjob and creating a lockfile and just have the script run every minute, but i feel like there may be a more effective way.

This script currently is written in python 2.7 on an ubuntu OS

Thanks for the help!

user2146933
  • 409
  • 5
  • 8
  • 16

7 Answers7

12

You could wrap your script in a

while True:
    ...

block, or with a bash script:

while true ; do
    yourpythonscript.py
done
Jasper
  • 3,939
  • 1
  • 18
  • 35
  • In the past, when i have done things similar to this, the script runs but eventually encounters a recursion depth error. Would such an error occur if i did it this way? – user2146933 Mar 27 '14 at 20:07
  • 1
    No, because there is no recursion. This would occur if your script calls itself at the end. – Jasper Mar 27 '14 at 20:27
  • Excellent, thank you for the help! This seems to be working and looping the script. – user2146933 Mar 27 '14 at 20:41
7

Try this:

os.execv(sys.executable, [sys.executable] + sys.argv)
Adrian B
  • 1,490
  • 1
  • 19
  • 31
  • 1
    This works perfectly! Add it after you call your main function or at the end of your code! After trying many solutions on here this was the best for me. – Olney1 Jul 23 '22 at 11:51
0

Wrap your code in a while statement:

while 1==1: #this will always happen
    yourscripthere
0

Ask it to run itself, with same arguments, should probably chmod +x it

os.execv(__file__, sys.argv)
Rami Dabain
  • 4,709
  • 12
  • 62
  • 106
0

you could also prompt your user if they would like to run the program again in a wrap.

prompt = input("would you like to run the program?")  
while prompt == "yes":  
...  
...  
prompt = input("would you like to run program again?")  
Ashkan S
  • 10,464
  • 6
  • 51
  • 80
fnky_mnky
  • 1
  • 2
0

Use the --wait in your shell script:

#!/bin/bash

while :
do
  sleep 5
  gnome-terminal --wait -- sh -c "python3 myscript.py 'myarg1'"
done
Chris
  • 18,075
  • 15
  • 59
  • 77
-4
while True:
    execfile("test.py")

This would keep executing test.py over and over.

femtoRgon
  • 32,893
  • 7
  • 60
  • 87