How to just call a command and not get its output

2019-01-22 18:09发布

问题:

This question already has an answer here:

  • How to hide output of subprocess in Python 2.7 6 answers

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.

回答1:

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.



回答2:

In case your process produces significant amounts of output that you don't want to buffer in memory, you should redirect the output to the electronic trash can:

with open(os.devnull, "w") as f:
    subprocess.call(["pdflatex", filename], stdout=f)

The variable os.devnull is the name of the null device of your operating system (/dev/null on most OSes, nul on the other one).



回答3:

just call it as you are and tack >/dev/null on the end of the comamnd. That will redirect any textual output.



回答4:

Use the /dev/null if you are using Unix. If you run any command in Shell and don't want to show its output on terminal.

For example :- ls > /dev/null will not produce any output on terminal.

So just use os,subprocess to execute some thing on shell and just put its o/p into /dev/null.