When scripting and automating tasks in Linux or any Unix-like operating system, you may come across instances where you need to use both Shell and Python scripts. Most often, it would involve passing arguments from a shell script to a Python script.
This tutorial will walk you through the steps to achieve this. The steps are easy to follow and designed keeping in mind those who are relatively new to shell scripting or Python.
Step 1: Pass Arguments to Shell Script
The first step is to create a shell script that can accept command-line arguments. You can pass command line arguments to a shell script by using special variables like $1 for the first argument, $2 for the second argument, and so on.
1 2 |
#!/bin/bash python3 script.py $1 $2 |
In this example, $1 and $2 are placeholders for the arguments that will be passed into the Python script named script.py.
Step 2: Passing Arguments from Shell Script to Python Script
Python access command-line arguments are accessed via the sys module. The argv is a list in Python, which contains the command-line arguments passed to the script.
1 2 3 4 |
import sys arg1 = sys.argv[1] arg2 = sys.argv[2] |
In the Python script, sys.argv is used to get the list of command-line arguments. arg1 and arg2 will hold the values passed from the shell script.
Step 3: Running the Shell Script
Run the shell script from the terminal. You need to pass the arguments while running the script. The syntax will be ./script.sh arg1 arg2.
The complete code now looks like this:
Full Code
1 2 |
#!/bin/bash python3 script.py $1 $2 |
1 2 3 4 |
import sys arg1 = sys.argv[1] arg2 = sys.argv[2] |
$1 $2
Conclusion
At this point, you should be able to pass arguments from a shell script to a Python script. This is a fundamental operation in scripting and programming and it is useful in many real-world applications, especially in automation tasks.