Run Shell Command And Capture Output in Python

Posted on July 31, 2019 at 3:52 pm

To run a shell command and capture the output in Python, use:

import subprocess
 
batcmd="ls"
 
result = subprocess.check_output(batcmd, shell=True)

With “shell=True” you will get the same behavior as os.system().

To capture the strerr use:

result = subprocess.check_output([batcmd], stderr=subprocess.STDOUT)

Receive updates via email

Other Posts

Updated Posts