Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign output of os.system to a variable and prevent it from being displayed on the screen [duplicate]

Tags:

python

I want to assign the output of a command I run using os.system to a variable and prevent it from being output to the screen. But, in the below code ,the output is sent to the screen and the value printed for var is 0, which I guess signifies whether the command ran successfully or not. Is there any way to assign the command output to the variable and also stop it from being displayed on the screen?

var = os.system("cat /etc/services") print var #Prints 0 
like image 866
John Avatar asked Aug 17 '10 15:08

John


People also ask

What is the purpose of the system () function in the OS module?

os. system() method execute the command (a string) in a subshell. This method is implemented by calling the Standard C function system(), and has the same limitations. If command generates any output, it is sent to the interpreter standard output stream.

What is OS Popen in Python?

Description. Python method popen() opens a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'. The bufsize argument has the same meaning as in open() function.


1 Answers

From "Equivalent of Bash Backticks in Python", which I asked a long time ago, what you may want to use is popen:

os.popen('cat /etc/services').read() 

From the docs for Python 3.6,

This is implemented using subprocess.Popen; see that class’s documentation for more powerful ways to manage and communicate with subprocesses.


Here's the corresponding code for subprocess:

import subprocess  proc = subprocess.Popen(["cat", "/etc/services"], stdout=subprocess.PIPE, shell=True) (out, err) = proc.communicate() print "program output:", out 
like image 125
Chris Bunch Avatar answered Sep 23 '22 05:09

Chris Bunch