How to call a shell script from python code?
Just run that shell script from Python with a speedy subprocess.run()
:
Be a good code soldier, always check those execute permissions (chmod +x script.sh
) and make sure of correct shebang usage (like #!/bin/bash
). This considers the script like you've run it straight from the terminal.
Feeding script with parameters
Passing arguments to the script
You want to give arguments? Just append them to the list:
Smart folks apply shlex.split()
for the argument's safe insertion when the command is already a string:
Catching the echo of script
Want to listen stdout and stderr? Then specify subprocess.PIPE
:
You're interested in output only? Just use subprocess.check_output()
:
Running the script with grace
Managing errors and exceptions
Be prepared for unexpected tantrums like subprocess.CalledProcessError
, which denotes non-zero exit statuses; they can't escape from the mighty try-except:
Check the exit status explicitly; extend your control lever to successful execution:
Advanced usage of subprocess
Need to craft complex interactions with the script, or manage advanced I/O? Embrace subprocess.Popen()
:
Safety first!
Prevent security vulnerabilities
Avoid shell=True
unless compulsory, as it may introduce security hazards, especially with unsanitized input. If you really need it, clean your inputs like a surgeon or stick to trusted values.
Maintain script's integrity
Your script should be as trustworthy as a guide dog. Let trusted sources provide your scripts, maintain them securely, and always review third-party scripts before running, because nobody wants a Trojan horse!
Workflows that flow
Bridging script and Python
Redirect script's chatter to Python to leverage Python's data processing strengths. Make your shell scripts and Python code work in harmony:
Automate like a pro with Python
Merge your Python script prowess with cron jobs or scheduling libraries like schedule
to automate tasks like a boss:
Not all environments are created equal
When scripts travel from dev to prod, they might face climate change. Avoid nasty surprises by using virtual environments, docker containers, or smart path strategies.
Was this article helpful?