简体   繁体   English

完成后如何重新启动python脚本

[英]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.我有一个将运行的 python 脚本,它基本上收集数据并根据上次更新数据库的时间将其插入到数据库中。 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.我考虑过使用 cronjob 并创建一个锁文件,然后每分钟运行一次脚本,但我觉得可能有更有效的方法。

This script currently is written in python 2.7 on an ubuntu OS该脚本目前是在 ubuntu 操作系统上用 python 2.7 编写的

Thanks for the help!谢谢您的帮助!

You could wrap your script in a您可以将脚本包装在

while True:
    ...

block, or with a bash script:块,或使用 bash 脚本:

while true ; do
    yourpythonscript.py
done

尝试这个:

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

Wrap your code in a while statement:将您的代码包装在 while 语句中:

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

要求它自己运行,使用相同的参数,可能应该chmod +x it

os.execv(__file__, sys.argv)

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

Use the --wait in your shell script:在 shell 脚本中使用 --wait :

#!/bin/bash

while :
do
  sleep 5
  gnome-terminal --wait -- sh -c "python3 myscript.py 'myarg1'"
done
while True:
    execfile("test.py")

This would keep executing test.py over and over.这将一遍又一遍地执行 test.py。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM