Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python - how to execute system command with no output

Tags:

python

Is there a built-in method in Python to execute a system command without displaying the output? I only want to grab the return value.

It is important that it be cross-platform, so just redirecting the output to /dev/null won't work on Windows, and the other way around. I know I can just check os.platform and build the redirection myself, but I'm hoping for a built-in solution.

like image 916
Gilad Naor Avatar asked Feb 01 '09 09:02

Gilad Naor


People also ask

How do I run a system command in Python?

If you need to execute a shell command with Python, there are two ways. You can either use the subprocess module or the RunShellCommand() function. The first option is easier to run one line of code and then exit, but it isn't as flexible when using arguments or producing text output.

How do you hide output in Python?

Data hiding in Python is done by using a double underscore before (prefix) the attribute name. This makes the attribute private/ inaccessible and hides them from users. Python has nothing secret in the real sense.

How do you execute a shell command in Python?

we are using the subprocess. Popen() method to execute the echo shell script using Python. You can give more arguments to the Popen function Object() , like shell=True, which will make the command run in a separate shell.


2 Answers

import os
import subprocess
subprocess.call(["ls", "-l"], stdout=open(os.devnull, "w"), stderr=subprocess.STDOUT)
like image 150
oefe Avatar answered Sep 19 '22 12:09

oefe


You can redirect output into temp file and delete it afterward. But there's also a method called popen that redirects output directly to your program so it won't go on screen.

like image 38
vava Avatar answered Sep 20 '22 12:09

vava