Leif Andersen
Leif Andersen

Reputation: 22342

Redirecting stdio from a command in os.system() in Python

Usually I can change stdout in Python by changing the value of sys.stdout. However, this only seems to affect print statements. So, is there any way I can suppress the output (to the console), of a program that is run via the os.system() command in Python?

Upvotes: 13

Views: 49883

Answers (5)

Piotr Czapla
Piotr Czapla

Reputation: 26582

I've found this answer while looking for a pythonic way to execute commands. The accepted answer has a deadlock if command waits for input. But it is not enough to just reverse read with write as you will have the deadlock if command writes larger output before it reads. The way to avoid this issue is to use p.communicate or even better Popen.run that does it for you.

Here are some examples:

To discard or read outputs:

>>> import subprocess
>>> r = subprocess.run("pip install fastai".split(), capture_output=True)
# you can ignore the result to discard it or read it
>>> r.stdout  
# and gets stdout as bytes

To pass something to the process use input:

>>> import subprocess
>>> subprocess.run("tr h H".split(), capture_output=True, text=True, input="hello").stdout
'Hello'

If you really don't want to deal with stdout, you can pass subprocess. DEVNULL to stdout and stderr as follows:

>>> import subprocess as sp
>>> sp.run("pip install fastai".split(), stdout=sp.DEVNULL, stderr=sp.DEVNULL).returncode
0

Upvotes: 0

ealdent
ealdent

Reputation: 3747

On a unix system, you can redirect stderr and stdout to /dev/null as part of the command itself.

os.system(cmd + "> /dev/null 2>&1")

Upvotes: 35

Blue Peppers
Blue Peppers

Reputation: 3808

You could consider running the program via subprocess.Popen, with subprocess.PIPE communication, and then shove that output where ever you would like, but as is, os.system just runs the command, and nothing else.

from subprocess import Popen, PIPE

p = Popen(['command', 'and', 'args'], stdout=PIPE, stderr=PIPE, stdin=PIPE)

output = p.stdout.read()
p.stdin.write(input)

Much more flexible in my opinion. You might want to look at the full documentation: Python Subprocess module

Upvotes: 17

Sean
Sean

Reputation: 623

If you want to completely eliminate the console that launches with the python program, you can save it with the .pyw extension.

I may be misunderstanding the question, though.

Upvotes: 0

mcandre
mcandre

Reputation: 24682

Redirect stderr as well as stdout.

Upvotes: 0

Related Questions