流程关闭

发布于 2024-09-08 22:49:31 字数 248 浏览 4 评论 0原文

我可以使用 python 子进程中的 Popen 来关闭已启动的进程吗?例如,我从 popen 运行一些应用程序。在我的代码的某些部分,我必须关闭该运行的应用程序。 例如,从 Linux 中的控制台我这样做:

./some_bin
... It works and logs stdout here ...
Ctrl + C and it breaks

我需要像 Ctrl + C 这样的东西,但在我的程序代码中。

can I use Popen from python subprocess to close started process? For example, from popen I run some application. In some part of my code I have to close that ran app.
For example, from console in Linux I do:

./some_bin
... It works and logs stdout here ...
Ctrl + C and it breaks

I need something like Ctrl + C but in my program code.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

静谧幽蓝 2024-09-15 22:49:31

使用 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()

Use the subprocess module.

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()
站稳脚跟 2024-09-15 22:49:31
from subprocess import Popen
process = Popen(['slow', 'running', 'program'])
while process.poll():
    if raw_input() == 'Kill':
        if process.poll(): process.kill()

kill() 将终止一个进程。在此处查看更多信息:Python 子进程模块

from subprocess import Popen
process = Popen(['slow', 'running', 'program'])
while process.poll():
    if raw_input() == 'Kill':
        if process.poll(): process.kill()

kill() will kill a process. See more here: Python subprocess module

总攻大人 2024-09-15 22:49:31

前段时间,我需要通过在 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()

Some time ago I needed a 'gentle' shutdown for a process by sending CTRL+C in Windows console.

Here's what I have:

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文