import subprocess
import time
py_file_dir = ["脚本1.py",
"脚本2.py",
]
for py_dir in py_file_dir:
py_file = "/data/" + py_dir #路径在/data/脚本1.py
command = f" pgrep -f 'python3.9 {py_file}'" #拿到脚本的进程号,
pid = subprocess.run(command, shell=True, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print("pid筛选结果,有值表示进程存在: ", pid.stdout)
if pid.stdout:
command2 = f"kill -9 {pid.stdout}"
result2 = subprocess.run(command2, shell=True, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(result2.stdout, f"kill python的进程 {pid.stdout}")
time.sleep(1)
command3 = f"nohup python3.9 {py_file} > /dev/null 2>&1 &"
result3 = subprocess.run(command3, shell=True, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(result3.stdout, f'重启python3.9进程,进程再后台运行 {py_file}')
else:
print('没有启用进程啊--')
command4 = f"nohup python3.9 {py_file} > /dev/null 2>&1 &"
result4 = subprocess.run(command4, shell=True, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(result4.stdout, f'没有就启动,现在开启进程 {py_file}')
time.sleep(3)