首页 > 解决方案 > 创建标志文件

问题描述

我对python比较陌生,所以请原谅早期的理解!

我正在努力创建一种标志文件。它的工作是监视 Python 可执行文件,标志文件不断运行并在可执行文件启动时打印“Start”,在运行时打印“Running”,在停止或崩溃时打印“Stop”,如果发生崩溃我希望它是能够重新启动脚本。到目前为止,我已经为重启做好了准备:

from subprocess import run
from time import sleep

# Path and name to the script you are trying to start
file_path = "py" 

restart_timer = 2
def start_script():
    try:
        # Make sure 'python' command is available
        run("python "+file_path, check=True) 
    except:
        # Script crashed, lets restart it!
        handle_crash()

def handle_crash():
    sleep(restart_timer)  # Restarts the script after 2 seconds
    start_script()

start_script()

我怎样才能将它与标志文件一起实现?

标签: pythonpython-3.x

解决方案


不确定“标志”是什么意思,但这最低限度地实现了你想要的。

主文件main.py

import subprocess
import sys
from time import sleep

restart_timer = 2
file_path = 'sub.py' # file name of the other process

def start():
    try:
        # sys.executable -> same python executable
        subprocess.run([sys.executable, file_path], check=True)
    except subprocess.CalledProcessError:
        sleep(restart_timer)
        return True
    else:
        return False

def main():
    print("starting...")
    monitor = True
    while monitor:
        monitor = start()

if __name__ == '__main__':
    main()

然后产生的过程称为sub.py

from time import sleep

sleep(1)
print("doing stuff...")

# comment out to see change
raise ValueError("sub.py is throwing error...")

将这些文件放入同一目录并运行它python main.py

您可以注释掉随机错误的抛出以查看主脚本正常终止。

更重要的是,这个例子并不是说它是实现所需质量的好方法......


推荐阅读