简体   繁体   English

检查python脚本是否正常运行以及是否没有重新运行?

[英]Check if a python script is running properly and if it isn't re-run it?

I have a script which is really buggy and every couple of hours it stops due to an error. 我有一个脚本,确实有错误,并且由于错误而每隔几个小时就会停止。 I don't code in Python but I know the basics so I would like to know how can I make a script that check another script for errors and if it's true just re-run it? 我不使用Python编写代码,但我了解基本知识,所以我想知道如何制作一个脚本来检查另一个脚本中的错误,如果真的是,请重新运行它? Sorry for not giving any examples but I think you get the idea and because I'm not good at Python doing this is easier than trying to understand the script and edit it. 抱歉,没有给出任何示例,但我想您已经明白了,并且因为我不擅长Python,所以这样做比尝试理解脚本并进行编辑要容易得多。 Any help is greatly appreciated. 任何帮助是极大的赞赏。

By far the simplest way is to just wait for it to exit and always restart it when it crashes; 到目前为止,最简单的方法是等待它退出,并在崩溃时始终重新启动它。 the following bash loop will do nothing while the program is running, and will restart it as soon as it exits: 在程序运行时,以下bash循环将不执行任何操作,并在退出后立即重新启动它:

while true
do
    python buggy_script.py arguments
    echo oops, restarting...
done

And that's it. 就是这样。 It'll run forever, until you kill the bash script that's running it. 它会永远运行,直到您杀死正在运行它的bash脚本为止。

PS. PS。 Of course this assumes you are on OS X or Linux; 当然,这假设您使用的是OS X或Linux; if you're on Windows, use an equivalent batch or PowerShell script. 如果您使用的是Windows,请使用等效的批处理或PowerShell脚本。

You can create a daemon for the script. 您可以为脚本创建一个守护程序。

Basically keep the main functionality in a loop that will run forever. 基本上将主要功能保持在一个可以永久运行的循环中。 import logging import time if __name__ == '__main__': while True: //log errors logging.basicConfig(filename='log_file.log', level=logging.DEBUG) // use try except to handle exceptions try: // your code statements and function calls except Exception as e: // log the error for debugging logging.error(str(e)) // sleep the program if you want it to for desired amount of time. time.sleep(delay)

The level of logging I set is debug. 我设置的日志记录级别是debug。 You can set it to any other of your own choice. 您可以将其设置为任何其他选择。

References : 参考文献:

Logging Docs - https://docs.python.org/3/library/logging.html 记录文档-https: //docs.python.org/3/library/logging.html

Handling exceptions - https://docs.python.org/3/tutorial/errors.html#handling-exceptions 处理异常-https: //docs.python.org/3/tutorial/errors.html#handling-exceptions

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

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