简体   繁体   English

如何确保 python 脚本在 Windows 上永远运行?

[英]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:我写了一个运行无限循环的 python 脚本,每半秒检查一次目录中是否有新文件:

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.该代码在 Windows 10 的 cmd 窗口中运行,我需要确保它永远不会停止。

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...): A)我需要找到一种机制(或几种机制)来在所有可能关闭的场景中重新启动脚本(如果仅在 2 分钟后重新启动就可以了......):

  1. if the computer is restarting如果计算机正在重新启动
  2. if someone close the cmd windows如果有人关闭 cmd 窗口
  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. B) 我希望每周一次主动关闭脚本并重新启动。

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. ps 我的第一个想法是 python 脚本只会检查新文件,计划的任务将每秒运行一次,但任务计划程序的最小间隔是 1 分钟。

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.由于您的脚本在 Windows 上运行,因此您可以使用Microsoft 任务计划程序(随 Windows 一起安装)在计算机启动时启动 Python 脚本。

  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.如果您不使用 cmd 窗口,您可以将 Python 脚本扩展名从.py更改为.pyw以在没有终端窗口的情况下运行脚本。 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 .要在发生异常后打开脚本,请查看此博客文章: 如何在异常发生后重新启动 Python 脚本并永远运行它

  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要每周重新启动一次脚本,您还可以使用答案 1 中提到的任务计划程序。我认为这篇文章可以帮助您重新启动脚本: Start and stop a python task

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

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