简体   繁体   English

从另一个 python 脚本终止 python 脚本

[英]Terminate a python script from another python script

I've got a long running python script that I want to be able to end from another python script.我有一个长时间运行的 python 脚本,我希望能够从另一个 python 脚本结束。 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.理想情况下,我正在寻找某种将进程 ID 设置为第一个脚本并能够通过第二个脚本的 ID 查看它是否正在运行的方法。 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.另外,我在 Windows 环境中工作。

I just recently found an alternative answer here: Check to see if python script is running我最近在这里找到了一个替代答案: 检查 python 脚本是否正在运行

You could get your own PID (Process Identifier) through您可以通过以下方式获得自己的 PID(进程标识符)

import os
os.getpid()

and to kill a process in Unix并在 Unix 中杀死一个进程

import os, signal
os.kill(5383, signal.SIGKILL)

to kill in Windows use在 Windows 中杀死

import subprocess as s
def killProcess(pid):
    s.Popen('taskkill /F /PID {0}'.format(pid), shell=True)

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.您可以将 PID 发送到其他程序,也可以在进程列表中搜索以查找其他脚本的名称并使用上述脚本将其杀死。

I hope that helps you.我希望这对你有帮助。

You're looking for the subprocess module .您正在寻找subprocess 模块

import subprocess as sp

extProc = sp.Popen(['python','myPyScript.py']) # runs myPyScript.py 

status = sp.Popen.poll(extProc) # status should be 'None'

sp.Popen.terminate(extProc) # closes the process

status = sp.Popen.poll(extProc) # status should now be something other than 'None' ('1' in my testing)

subprocess.Popen starts the external python script, equivalent to typing 'python myPyScript.py' in a console or terminal. subprocess.Popen 启动外部 python 脚本,相当于在控制台或终端中键入“python myPyScript.py”。

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.如果进程仍在运行,则来自 subprocess.Popen.poll(extProc) 的状态将为“无”,如果它已从该脚本中关闭,则(对我而言)为 1。 Not sure about what the status is if it has been closed another way.如果它以其他方式关闭,不确定它的状态。

This worked for me under windows 11 and PyQt5: subprocess.Popen('python3 MySecondApp.py') Popen.terminate(app)这在 windows 11 和 PyQt5 下对我有用: subprocess.Popen('python3 MySecondApp.py') Popen.terminate(app)

where app is MyFirstApp.py (the caller script, running) and MySecondApp.py (the called script)其中 app 是 MyFirstApp.py(调用者脚本,正在运行)和 MySecondApp.py(被调用脚本)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM