[英]How to restart a python script using another?
(“第一个脚本”从用户那里获取输入,“第二个脚本”通知任务。)
我一直在尝试使用另一个脚本重新启动 python 脚本,但是在尝试了几种方法后我无法成功。 我开发了一个提醒,当用户之前设置的时间到达时通知用户,应用程序在 Linux 上运行,它有 2 个 python 脚本。 第一个是接受用户提供的输入来安排任务。 例如,“下午 12:30 打电话给老板”。 然后 Linux 将在下午 12:30 通知它。 另一个是检查输入并在时间到来时通知他们。
在第一个脚本中,我试图在用户给出新任务时重新启动另一个脚本,因为脚本需要读取新任务来通知它。 我还想在运行第二个脚本时终止第一个脚本。 但是第二个脚本必须仍然有效。 在第一个脚本中,我尝试了这些命令来做到这一点:
os.system(f"pkill -f {path2}")
os.system(f"python {path2}")
这些都行不通。
另外我想在我的操作系统启动时运行第二个脚本。
概括:
1-我想使用另一个脚本重新启动 python 脚本,并且在运行第二个脚本时应该终止第一个脚本。
2-我想在我的操作系统启动时运行第二个脚本。
关于我的提醒应用程序的存储库在这里。
关于1:
假设另一个脚本的名称是 2.py(可使用下面的代码更改),这对我来说非常有效:
1.py:
import subprocess
import os
import time
OTHER_SCRIPT_NAME = "2.py"
process_outputs = subprocess.getoutput("ps aux | grep " + OTHER_SCRIPT_NAME) # Searching for the process running 2.py
wanted_process_info = process_outputs.split("\n")[0] # Getting the first line only
splitted_process_info = wanted_process_info.split(" ") # Splitting the string
splitted_process_info = [x for x in splitted_process_info if x != ''] # Removing empty items
pid = splitted_process_info[1] # PID is the secend item in the ps output
os.system("kill -9 " + str (pid)) # Killing the other process
exit()
time.sleep(1000) # Will not be called because exit() was called before
2.py:
import time
time.sleep(100)
关于2:
在 linux 中,您可以通过将脚本写入/etc/rc.local
文件来在启动时执行脚本
只需从 rc.local 文件运行您的脚本,您就可以使用 go:
/etc/rc.local:
python '/path/to/your/scripts'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.