你想要监控一个Python可执行文件,有许多方面的信息能够被跟踪,如运行时间、执行状态、错误或异常等。以下是一个简单的监控接口示例,我们会定期检查脚本的运行状态,并记录每次运行的时间。
`monitor.py`:
```python
import os
import time
import subprocess
from datetime import datetime
class PythonScriptMonitor:
def __init__(self, script_path):
self.script_path = script_path
self.process = None
self.log_file = 'monitor_log.txt'
self.interval = 5
def start_script(self):
print('启动脚本...')
self.process = subprocess.Popen(['python3', self.script_path])
def monitor_script(self):
while True:
if self.process.poll() is not None:
print("Python脚本已经停止运行,正在重新启动...")
self.record_log('Stopped')
self.start_script()
self.record_log('Started')
time.sleep(self.interval)
def stop_script(self):
print('停止脚本...')
self.process.kill()
self.record_log('Manually Stopped')
def record_log(self, status):
now = datetime.now()
current_time = now.strftime("%d/%m/%Y, %H:%M:%S")
with open(self.log_file, 'a') as f:
f.write(f'{current_time}: {self.script_path} - {status}\n')
if __name__ == "__main__":
monitor = PythonScriptMonitor('your_script.py')
monitor.start_script()
monitor.record_log('Started')
try:
monitor.monitor_script()
except KeyboardInterrupt:
monitor.stop_script()
```
在以上的`monitor.py`中,我们假设你要监控的Python执行文件为`your_script.py`。如果你需要监控其他Python执行文件,只需替换此文件名。
当你运行`monitor.py`,它将启动你指定的python脚本,并定期检查他的运行状态。如果发现脚本已经停止,例如由于错误或其他情况,它将自动重新启动脚本,并将所有操作写入监控日志`monitor_log.txt`。如果你想要停止监控,可以直接停止`monitor.py`脚本,它将记录下被手动停止的状态。
为保证工作的正确性,你需要确保你的运行环境已经安装`subprocess`库。
这个是一个基础的Python执行文件监控行为,你可以根据你的需求进行扩展,例如增加邮件通知等。