从另一个 python 脚本终止一个 python 脚本
我有一个长时间运行的 python 脚本,我希望能够从另一个 python 脚本结束它。理想情况下,我正在寻找一种为第一个脚本设置进程 ID 的方法,并能够通过第二个脚本的 ID 查看它是否正在运行。此外,我希望能够终止那个长时间运行的进程。
有什么很酷的捷径可以实现这一点吗?
另外,我正在 Windows 环境中工作。
我最近在这里找到了一个替代答案: 检查 python 脚本是否运行
I've got a long running python script that I want to be able to end from another python script. Ideally what I'm looking for is some way of setting a process ID to the first script and being able to see if it is running or not via that ID from the second. Additionally, I'd like to be able to terminate that long running process.
Any cool shortcuts exist to make this happen?
Also, I'm working in a Windows environment.
I just recently found an alternative answer here: Check to see if python script is running
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以通过获取自己的 PID(进程标识符)
并在 Unix 中杀死进程,
在 Windows 中杀死进程。
您可以将 PID 发送给其他程序,或者您可以在进程列表中搜索以查找其他脚本的名称,然后用上面的脚本杀死它。
我希望这对你有帮助。
You could get your own PID (Process Identifier) through
and to kill a process in Unix
to kill in Windows use
You can send the PID to the other programm or you could search in the process-list to find the name of the other script and kill it with the above script.
I hope that helps you.
您正在寻找子流程模块。
subprocess.Popen 启动外部 python 脚本,相当于在控制台或终端中输入“python myPyScript.py”。
如果进程仍在运行,则 subprocess.Popen.poll(extProc) 的状态将为“无”;如果进程已从此脚本中关闭,则(对我来说)为 1。不确定是否以其他方式关闭了状态。
You're looking for the subprocess module.
subprocess.Popen starts the external python script, equivalent to typing 'python myPyScript.py' in a console or terminal.
The status from subprocess.Popen.poll(extProc) will be 'None' if the process is still running, and (for me) 1 if it has been closed from within this script. Not sure about what the status is if it has been closed another way.
这在 Windows 11 和 PyQt5 下对我有用:
其中 app 是
MyFirstApp.py
(调用者脚本,正在运行)和MySecondApp.py
(被调用的脚本)This worked for me under windows 11 and PyQt5:
where app is
MyFirstApp.py
(the caller script, running) andMySecondApp.py
(the called script)