Skip to content

Instantly share code, notes, and snippets.

@bmcculley
Created September 28, 2019 02:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmcculley/8b42d5be5d53e7f347413fca3295450b to your computer and use it in GitHub Desktop.
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.
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'))
@bmcculley
Copy link
Author

The original code for this was taken from https://linuxhandbook.com/execute-shell-command-python/

@KuaJnio
Copy link

KuaJnio commented Nov 25, 2019

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