The task of executing shell commands programmatically and capturing their output as a string can be accomplished with the help of Python's subprocess module.
For the simplest approach in officially maintained Python versions, utilize the check_output function:
import subprocess output = subprocess.check_output(['ls', '-l']) print(output) # Output: b'total 0\n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 files\n'
In Python 3.5 , the run function provides a more flexible and modern approach:
import subprocess result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE) print(result.stdout.decode('utf-8')) # Output: 'total 0\n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 files\n'
For extended compatibility and advanced functionality, use the low-level Popen constructor. With communicate, you can capture output and pass input:
import subprocess p = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE) output, _ = p.communicate() print(output) # Output: b'.\n..\nfoo\n'
Shell Command Execution (shell=True Argument)
By default, the functions execute single programs. To execute complex shell commands, set shell=True. However, this raises security concerns.
Input Handling
To pass input via stdin, specify the input keyword argument in run or Popen.
Error Handling
For proper error handling, use check_output with stdout=subprocess.STDOUT or Popen with stderr=subprocess.STDOUT. Alternatively, check the subprocess returncode.
The above is the detailed content of How Can I Run Shell Commands and Capture Their Output in Python?. For more information, please follow other related articles on the PHP Chinese website!