orezvani
orezvani

Reputation: 3775

How to pipe the output of a command to `/dev/null` in python

I am trying to pipe the output of the following command to /dev/null so that it doesn't get printed for the user that is running the program.

import os
os.system("ping -c 1 192.168.unknown.host > /dev/null")

But I get the error:

ping: unknown host  192.168.unknown.host

The problem is that this message is produced by something other than stdout, probably stderr and I can easily redirect it to /dev/null using

ping -c 1 192.168.unknown.host >& /dev/null

However, when I use that in python, I get the following error:

sh: 1: Syntax error: Bad fd number

Is it possible to solve this? (I just don't want that message to be printed).

Upvotes: 1

Views: 7626

Answers (2)

Bartosz Marcinkowski
Bartosz Marcinkowski

Reputation: 6861

import subprocess

subprocess.Popen(
    ['ping', "-c", "192.168.unknown.host"],
    stdout=subprocess.DEVNULL,
    stderr=subprocess.DEVNULL,
)

As pointed out by Ashwini Chaudhary, for Python below 3.3 you have to manually open os.devnull:

import os
import subprocess

with open(os.devnull, 'w') as DEVNULL:
    subprocess.Popen(
        ['ping', "-c", "192.168.unknown.host"],
        stdout=DEVNULL,
        stderr=DEVNULL,
    )

Upvotes: 10

ofrommel
ofrommel

Reputation: 2177

You should take a look at the Python subprocess module. It offers several methods that can handle standard input, output and error.

Something like this:

import subprocess as sub
import shlex

cmd = "ping -c 1 myhost"
cmdarg = shlex.split(cmd)
p = sub.Popen(cmdarg,stdout=sub.PIPE,stderr=sub.PIPE)
output, errors = p.communicate()

Upvotes: 2

Related Questions