简体   繁体   中英

How to make sure that python script will run forever on windows?

I wrote a python script that run an infinite loop and every half second checks if there are new files in a directory:

while True:
    files = os.listdir(path_to_dir)
    # do something
    time.sleep(0.5)

The code runs on windows 10 in a cmd window and I need to make sure it will never stop.

A) I need to find a mechanism (or few mechanisms) that will restart the script in all possible scenarios that it might turn off (it is ok if the restart will happen only 2 minutes later...):

  1. if the computer is restarting
  2. if someone close the cmd windows
  3. if the script end unexpectedly because of unhandle exception or memory leak (it is not suppose to happen...)

B) I want that once in a week, proactively,the script will be turn off and restart.

Any ideas? Thanks!!

ps my first idea was that the python script will only check for new file, and the task scheduled will run it every second, but the minimum interval for task scheduler is 1 minute.

I think these answer all your questions:

  1. Since your script runs on windows, you can use the Microsoft Task Scheduler (which is installed with Windows) to start your Python script when your computer starts up.

  2. If you do not use the cmd window, you can change your Python script extention from .py to .pyw to run the script without a terminal window. A bit more on that here: Executing scripts .

  3. For opening the script after an exception has happend, have a look at this blog post: How to Restart Python Script after Exception and Run it Forever .

  4. To restart your script once a week, you can also use the Task Scheduler mentioned in answer 1. I think this post could help you with restarting your script: Start and stop a python task

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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