在 Python 中禁用 subprocess.Popen 的控制台输出

发布于 2024-08-01 19:48:17 字数 280 浏览 7 评论 0原文

我在 Windows 上运行 Python 2.5,并且在代码中的某个位置我必须

subprocess.Popen("taskkill /PID " + str(p.pid))

通过 pid 终止 IE 窗口。 问题是,如果没有在 Popen 中设置管道,我仍然会输出到控制台 - SUCCESS: PID 2068 的进程已终止。 我将其调试到 subprocess.py 中的 CreateProcess,但无法从那里开始。

有人知道如何禁用此功能吗?

I run Python 2.5 on Windows, and somewhere in the code I have

subprocess.Popen("taskkill /PID " + str(p.pid))

to kill IE window by pid. The problem is that without setting up piping in Popen I still get output to console - SUCCESS: The process with PID 2068 has been terminated. I debugged it to CreateProcess in subprocess.py, but can't go from there.

Anyone knows how to disable this?

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

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

发布评论

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

评论(2

舂唻埖巳落 2024-08-08 19:48:17
from subprocess import check_call, DEVNULL, STDOUT

check_call(
    ("taskkill", "/PID", str(p.pid)),
    stdout=DEVNULL,
    stderr=STDOUT,
)

我总是将元组(或列表)传递给子进程,因为它让我不用担心逃脱。 check_call 确保 (a) 子进程在管道关闭之前完成,并且 (b) 被调用进程中的失败不会被忽略。

如果您陷入 python 2,子进程不提供 DEVNULL。 但是,您可以通过打开 os.devnull 来复制它(Python 2.4+ 中表示 NUL 的标准跨平台方式):

import os
from subprocess import check_call, STDOUT

DEVNULL = open(os.devnull, 'wb')
try:
    check_call(
        ("taskkill", "/PID", str(p.pid)),
        stdout=DEVNULL,
        stderr=STDOUT,
    )
finally:
    DEVNULL.close()
from subprocess import check_call, DEVNULL, STDOUT

check_call(
    ("taskkill", "/PID", str(p.pid)),
    stdout=DEVNULL,
    stderr=STDOUT,
)

I always pass in tuples (or lists) to subprocess as it saves me worrying about escaping. check_call ensures (a) the subprocess has finished before the pipe closes, and (b) a failure in the called process is not ignored.

If you're stuck in python 2, subprocess doesn't provide DEVNULL. However, you can replicate it by opening os.devnull (the standard, cross-platform way of saying NUL in Python 2.4+):

import os
from subprocess import check_call, STDOUT

DEVNULL = open(os.devnull, 'wb')
try:
    check_call(
        ("taskkill", "/PID", str(p.pid)),
        stdout=DEVNULL,
        stderr=STDOUT,
    )
finally:
    DEVNULL.close()
飘过的浮云 2024-08-08 19:48:17
fh = open("NUL","w")
subprocess.Popen("taskkill /PID " + str(p.pid), stdout = fh, stderr = fh)
fh.close()
fh = open("NUL","w")
subprocess.Popen("taskkill /PID " + str(p.pid), stdout = fh, stderr = fh)
fh.close()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文