进程关闭
我可以用Python的subprocess模块里的Popen来关闭已经启动的进程吗?比如,我通过Popen运行了一个应用程序。在我代码的某个部分,我需要关闭这个运行中的应用。
举个例子,在Linux的控制台里,我可以这样做:
./some_bin
... It works and logs stdout here ...
Ctrl + C and it breaks
我需要在我的程序代码里实现类似于按下Ctrl + C的功能。
3 个回答
0
不久前,我需要在Windows控制台中通过发送CTRL+C来“温和”地关闭一个进程。
这是我所写的代码:
import win32api
import win32con
import subprocess
import time
import shlex
cmdline = 'cmd.exe /k "timeout 60"'
args = shlex.split(cmdline)
myprocess = subprocess.Popen(args)
pid = myprocess.pid
print(myprocess, pid)
time.sleep(5)
win32api.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, pid)
# ^^^^^^^^^^^^^^^^^^^^ instead of myprocess.terminate()
3
使用 subprocess
模块。
import subprocess
# all arguments must be passed one at a time inside a list
# they must all be string elements
arguments = ["sleep", "3600"] # first argument is the program's name
process = subprocess.Popen(arguments)
# do whatever you want
process.terminate()
2
from subprocess import Popen
process = Popen(['slow', 'running', 'program'])
while process.poll():
if raw_input() == 'Kill':
if process.poll(): process.kill()
kill()
是用来结束一个正在运行的程序的。想了解更多,可以查看这里:Python 子进程模块