如何只调用命令而不获取其输出 [英] How to just call a command and not get its output

查看:30
本文介绍了如何只调用命令而不获取其输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,通过 subprocess 调用命令但不打扰其输出的最短和标准方法是什么.

我尝试了 subprocess.call 但它似乎返回了输出.我不介意这个,我只需要安静地运行程序,而输出不会弄乱屏幕.

如果有帮助,我正在调用 pdflatex 并且我的目的只是调用它.

解决方案

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)出,错误 = p.communicate()# 做一些事情,错误,或者完全不打扰.

基本上,这个管道"将 cmd 输出到 stdout 和 stderr 到由 subprocess 准备的内存缓冲区.您如何处理这些缓冲区的内容取决于您.您可以检查它们,或者完全不理会它们.但是管道到这些缓冲区的副作用是它们不会被打印到终端.

edit:这也适用于便利方法 call.演示:

<预><代码>>>>subprocess.call('ping 127.0.0.1')用 32 字节的数据 Ping 127.0.0.1:来自 127.0.0.1 的回复:bytes=32 time<1ms TTL=128来自 127.0.0.1 的回复:bytes=32 time<1ms TTL=128来自 127.0.0.1 的回复:bytes=32 time<1ms TTL=128来自 127.0.0.1 的回复:bytes=32 time<1ms TTL=128127.0.0.1 的 Ping 统计信息:数据包:发送 = 4,接收 = 4,丢失 = 0(0% 丢失),大约以毫秒为单位的往返时间:最小值 = 0ms,最大值 = 0ms,平均值 = 0ms0>>>subprocess.call('ping 127.0.0.1', stdout=subprocess.PIPE)0

edit-2:注意事项subprocess.call:

<块引用>

注意:不要将 stdout=PIPE 或 stderr=PIPE 与此函数一起使用.作为当前进程中没有读取管道,子进程可能如果它生成足够的输出到管道以填满 OS 管道,则阻塞缓冲.

In Python, what is the shortest and the standard way of calling a command through subprocess but not bothering with its output.

I tried subprocess.call however it seems to return the output. I am not bothered with that, I just need to run the program silently without the output cluttering up the screen.

If it helps, I am callling pdflatex and my intention is just to call it.

解决方案

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
# do something with out, err, or don't bother altogether.

Basically, this "pipes" whatever cmd outputs to stdout and stderr to in-memory buffers prepared by subprocess. What you do with the content of those buffers are up to you. You can examine them, or don't bother with them altogether. But the side effect of piping to these buffers is that they won't be printed to the terminal's.

edit: This also works with the convenience method, call. For a demonstration:

>>> subprocess.call('ping 127.0.0.1')

Pinging 127.0.0.1 with 32 bytes of data:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128

Ping statistics for 127.0.0.1:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum = 0ms, Average = 0ms
0
>>> subprocess.call('ping 127.0.0.1', stdout=subprocess.PIPE)
0

edit-2: A note of caution for subprocess.call:

Note: Do not use stdout=PIPE or stderr=PIPE with this function. As the pipes are not being read in the current process, the child process may block if it generates enough output to a pipe to fill up the OS pipe buffer.

这篇关于如何只调用命令而不获取其输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆