user2146933
user2146933

Reputation: 407

How to restart a python script after it finishes

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!

Upvotes: 10

Views: 29734

Answers (7)

Chris
Chris

Reputation: 18884

Use the --wait in your shell script:

#!/bin/bash

while :
do
  sleep 5
  gnome-terminal --wait -- sh -c "python3 myscript.py 'myarg1'"
done

Upvotes: 0

fnky_mnky
fnky_mnky

Reputation: 1

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?")  

Upvotes: 0

TeAmEr
TeAmEr

Reputation: 4773

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

os.execv(__file__, sys.argv)

Upvotes: 0

awesomeshreyo
awesomeshreyo

Reputation: 15

Wrap your code in a while statement:

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

Upvotes: 0

Adrian B
Adrian B

Reputation: 1631

Try this:

os.execv(sys.executable, [sys.executable] + sys.argv)

Upvotes: 7

shilpa sangappa
shilpa sangappa

Reputation: 5

while True:
    execfile("test.py")

This would keep executing test.py over and over.

Upvotes: -4

Jasper
Jasper

Reputation: 3947

You could wrap your script in a

while True:
    ...

block, or with a bash script:

while true ; do
    yourpythonscript.py
done

Upvotes: 12

Related Questions