Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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

1 Answer

0 votes
by (106k points)

For assign output of os.system to a variable and prevent it from being displayed on the screen you can use 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)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...