Ogs
Ogs

Reputation: 166

What is the difference between os.devnull and subprocess.pipe?

I've been trying out how not to print shell outputs from Python's subprocess.call() by assigning open(os.devnull, 'w') and subprocess.PIPE to the stdout value:

subprocess.call(command, stdout=open(os.devnull, 'w'), shell=True)

and

subprocess.call(command, stdout=subprocess.PIPE, shell=True)

Both these lines execute the shell command stored in the command variable discreetly i.e. without outputting on the terminal. However, I don't know the difference between the two. I am new to using subprocess.

/ogs

Upvotes: 1

Views: 8536

Answers (2)

CandyCrusher
CandyCrusher

Reputation: 316

The first method is to redirect the standard output to a file (/dev/null in POSIX), while the second one is to build a PIPE to redirect the output to a specific stream.

The official definition of subprocess.PIPE referred from command help(): "This module allows you to spawn processes, connect to their input/output/error pipes, and obtain their return codes."

I would say this method is like: we just put something in a message queue(memory) for a while for later use. But subprocess.call just return the status code. It seems you cannot refer the return value for subprocess.call(command, stdout=open(os.devnull, 'w'), shell=True) so that you cannot refer the value by subprocess.call(command, stdin=the_stdout, shell=True). It is hard to build a connection between two commands.

Based on the info in this article: http://blog.acipo.com/running-shell-commands-in-python/

Also Python 2.7 Documentation: https://docs.python.org/2/library/subprocess.html

It is recommended that we may use Popen with communicate()

Popen is an advanced class provided by Python 3. There is a good resource about this: https://stackabuse.com/pythons-os-and-subprocess-popen-commands/

Upvotes: 5

sanerersan
sanerersan

Reputation: 31

devnull is a point to /dev/null in Linux. When you write to /dev/null, it will discard everything received.

pipe has two ends, when you write to one end, the other pipe will receive the message you wrote.

Upvotes: 3

Related Questions