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
  • 389
  • 4
  • 7
  • 16

7 Answers7

11

You could wrap your script in a

while True:
    ...

block, or with a bash script:

while true ; do
    yourpythonscript.py
done
Jasper
  • 3,840
  • 1
  • 17
  • 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
6

Try this:

os.execv(sys.executable, [sys.executable] + sys.argv)
Adrian B
  • 1,178
  • 1
  • 14
  • 28
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,581
  • 12
  • 59
  • 104
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
  • 8,950
  • 5
  • 46
  • 73
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
  • 16,237
  • 15
  • 56
  • 75
-4
while True:
    execfile("test.py")

This would keep executing test.py over and over.

femtoRgon
  • 32,075
  • 7
  • 57
  • 84