How to Run Shell Command from Python: Simple Guide
You can run shell commands in Python using the
subprocess.run() function, which executes the command and waits for it to finish. Use subprocess.run(['command', 'arg1', 'arg2']) for safe execution without a shell, or add shell=True to run the command through the shell.Syntax
The basic syntax to run a shell command in Python is using the subprocess.run() function. You pass the command as a list of strings or as a single string with shell=True. The function waits for the command to complete and returns a result object.
- command: List of command and arguments or a string if
shell=True. - shell: Boolean to decide if command runs through the shell.
- capture_output: If
True, captures the command output.
python
import subprocess # Run command without shell result = subprocess.run(['ls', '-l'], capture_output=True, text=True) # Run command with shell result_shell = subprocess.run('ls -l', shell=True, capture_output=True, text=True)
Example
This example shows how to run the echo command to print text from Python and capture its output.
python
import subprocess result = subprocess.run(['echo', 'Hello from Python'], capture_output=True, text=True) print('Output:', result.stdout.strip())
Output
Output: Hello from Python
Common Pitfalls
Common mistakes include:
- Using
shell=Trueunnecessarily, which can be a security risk if input is not trusted. - Passing the command as a string without
shell=True, which causes errors. - Not capturing output and missing command results.
python
import subprocess # Wrong: string command without shell=True # subprocess.run('ls -l') # This will raise an error # Right: list command without shell subprocess.run(['ls', '-l']) # Or string command with shell=True subprocess.run('ls -l', shell=True)
Quick Reference
Remember these tips when running shell commands from Python:
- Use
subprocess.run()for simple command execution. - Pass commands as a list for safety and avoid
shell=Truewhen possible. - Use
capture_output=Trueandtext=Trueto get command output as a string. - Be cautious with
shell=Trueto avoid security risks.
Key Takeaways
Use subprocess.run() to execute shell commands safely from Python.
Pass commands as a list of strings to avoid shell injection risks.
Use capture_output=True and text=True to capture and read command output.
Avoid shell=True unless necessary and input is trusted.
Always handle command results to check for success or errors.