python - 创建标志文件
问题描述
我对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()
我怎样才能将它与标志文件一起实现?
解决方案
不确定“标志”是什么意思,但这最低限度地实现了你想要的。
主文件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
您可以注释掉随机错误的抛出以查看主脚本正常终止。
更重要的是,这个例子并不是说它是实现所需质量的好方法......
推荐阅读
- oracle - 循环遍历数组以获取 where 条件 pl/sql
- php - 在codeigniter中上传图片Rest api
- android - 在特定设备上使用 Let's Encrypt 的 ERR_SSL_PROTOCOL_ERROR
- java - 无法使用 Groovy/Grails Tool Suite 在 grails 项目中打开文件
- stata - 使用制表符时删除列
- android - 如何在 OnDestroy 中关闭运行时权限对话框?
- laravel - Lumen 在执行 phpunit 时不会迁移包表
- css - 如何将第三方样式标记为@media screen {}
- facebook - 创建 Facebook 广告帐户沙盒帐户并解锁 ads_read -(AKA:从 facebook 开始阅读入门教程)
- twilio - 如果我使用的是 Twilio Flex,那么我是否只需要自定义 UI 并从头开始构建 API?