Created
September 28, 2019 02:38
-
-
Save bmcculley/8b42d5be5d53e7f347413fca3295450b to your computer and use it in GitHub Desktop.
An example of running a shell command from python and capturing its output.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import subprocess | |
MyOut = subprocess.Popen(['ls', '-l', '.'], | |
stdout=subprocess.PIPE, | |
stderr=subprocess.STDOUT) | |
stdout,stderr = MyOut.communicate() | |
if stdout: | |
print(stdout.decode('utf-8')) | |
if stderr: | |
print(stderr.decode('utf-8')) |
Note that you can specify the encoding in the call instead of decoding it after:
MyOut = subprocess.Popen(['ls', '-l', '.'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
encoding='utf8')
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The original code for this was taken from https://linuxhandbook.com/execute-shell-command-python/