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?
For python 3.5+ it is recommended that you use the run function from the subprocess module. This returns a
CompletedProcess object, from which you can easily obtain the output as well as return code. Since you are only interested in the output, you can write a utility wrapper like this.
from subprocess import PIPE, run def out(command): result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True, shell=True) return result.stdout my_output = out("echo hello world") print(my_output)