How to Call a Python Script from Bash

How to Call a Python Script from Bash

Integrating Python scripts with Bash is a common requirement for automation, data processing, and system administration tasks. Whether you're a developer or a DevOps engineer, knowing how to execute Python code from the command line efficiently can save time and streamline workflows.

Basic Method: Using the Python Interpreter

The simplest way to run a Python script from Bash is by invoking the Python interpreter directly. Here's how:

python3 script_name.py

Replace script_name.py with your Python file's name. If you're using Python 2 (though it's outdated), replace python3 with python.

Passing Arguments to the Script

You can pass command-line arguments to your Python script like this:

python3 script_name.py arg1 arg2 arg3

In your Python script, use the sys.argv list from the sys module to access these arguments:

import sys

if __name__ == "__main__":
    print("Arguments passed:", sys.argv)

Using Shebang for Direct Execution

For a more seamless experience, add a shebang line at the top of your Python script to specify the interpreter:

#!/usr/bin/env python3

Then, make the script executable using chmod:

chmod +x script_name.py

Now, you can run the script directly:

./script_name.py

Advanced: Capturing Output in Bash

You can capture the output of a Python script in a Bash variable for further processing:

output=$(python3 script_name.py)
echo "Python script output: $output"

Error Handling

Check the exit status of your Python script in Bash to handle errors:

if python3 script_name.py; then
    echo "Script executed successfully"
else
    echo "Script failed"
fi

Using Subprocess Module for Complex Integrations

For more complex scenarios, the subprocess module in Python allows you to call Bash commands from Python and vice versa. Here's an example:

import subprocess

result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
print(result.stdout.decode('utf-8'))

This runs the ls -l command in Bash and captures its output in Python.

Summary: Learn how to execute Python scripts from Bash using basic commands, shebang, and advanced techniques like output capture and error handling. The subprocess module is widely used for bidirectional integration.

Incoming search terms
- How to call a Python script from Bash command line
- Best way to execute Python script in terminal
- Passing arguments to Python script from Bash
- Running Python scripts directly without python command
- How to make Python script executable in Linux
- Capture Python script output in Bash variable
- Error handling when calling Python from Bash
- Using shebang for Python scripts in Unix
- How to integrate Python and Bash scripts
- Running Python 3 scripts from command line

No comments:

Post a Comment