'Python - Run shell command, get stdout and stderr as a variable, but hide from user?
I would like to have my Python script run a Linux shell command and store the output in a variable, without the command's output being shown to the user. I have tried this with os.system, subprocess.check_output, subprocess.run, subprocess.Popen, and os.popen with no luck.
My current method is running os.system("ls -l &> /tmp/test_file") so the command stdout and stderr are piped to /tmp/test_file, and then I have my python code read the file into a variable and then delete it.
Is there a better way of doing this so that I can have the command output sent directly into the variable without having to create and delete a file, but keep it hidden from the user?
Thanks
Solution 1:[1]
You can use subprocess.run function.
from subprocess import run
data = run("ANY COMMAND HERE",capture_output=True,shell=True)
print(data.stdout)
print(data.stderr)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sharim Iqbal |
