Python is an incredibly versatile and user-friendly scripting language that enables automation and simplification of repetitive tasks.
It’s important to know how to execute a Python script with arguments, which allows you to pass different values to the script when running it.
This tutorial will guide you through the process of executing a Python script with arguments using the command line and within the script.
Step 1: Create a Python Script
To execute a Python script with arguments, we’ll create a simple Python script that accepts two command-line arguments and performs arithmetic operations. This is a basic example to demonstrate how to handle arguments in a Python script.
Create a new file called calc.py and add the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import sys def main(a, b): print("Sum:", a + b) print("Difference:", a - b) print("Product:", a * b) print("Division:", a / b) if __name__ == "__main__": if len(sys.argv) == 3: num1 = int(sys.argv[1]) num2 = int(sys.argv[2]) main(num1, num2) else: print("Usage: python calc.py num1 num2") sys.exit(1) |
In this script, we import the sys
module, which contains the argv
list that holds command-line arguments. We then define the main
function that takes two input numbers and computes their sum, difference, product, and division.
The script checks if there are exactly three command-line arguments (the script name and two numbers) provided. If it’s true, it converts the second and third arguments to integers and calls the main
function. Otherwise, it prints a usage message and exits the program with a non-zero status code.
Step 2: Executing the Python Script with Arguments
Now that you have created the calc.py script, you can execute the code from the command line with different numbers as arguments. Make sure you have Python installed on your system and navigate to the directory where your script is saved.
To run the script, type the following command:
1 |
python calc.py 10 5 |
This will execute the script with the given parameters (10 and 5 in this case), and you should see the following output:
Sum: 15 Difference: 5 Product: 50 Division: 2.0
You can also try the script with other numbers to see the responses updated accordingly.
Step 3: Error Handling and Validation
Although the script is functional, we can improve it by adding error handling and input validation. It’s a good practice to make your script more robust, especially if it will be used by others or in a production environment.
In this example, we’ll add input validation for only integer values and handle the potential division with zero error. Modify the calc.py script with the following changes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import sys def main(a, b): print("Sum:", a + b) print("Difference:", a - b) print("Product:", a * b) if b != 0: print("Division:", a / b) else: print("Cannot divide by zero") if __name__ == "__main__": if len(sys.argv) == 3: try: num1 = int(sys.argv[1]) num2 = int(sys.argv[2]) main(num1, num2) except ValueError: print("Both arguments must be integers") sys.exit(1) else: print("Usage: python calc.py num1 num2") sys.exit(1) |
Now, if you try to pass a non-integer argument or divide by zero, the script will handle these errors correctly.
1 |
python calc.py 10 a |
Both arguments must be integers
1 |
python calc.py 10 0 |
Sum: 10 Difference: 10 Product: 0 Cannot divide by zero
Full Code
Here is the final version of the calc.py script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import sys def main(a, b): print("Sum:", a + b) print("Difference:", a - b) print("Product:", a * b) if b != 0: print("Division:", a / b) else: print("Cannot divide by zero") if __name__ == "__main__": if len(sys.argv) == 3: try: num1 = int(sys.argv[1]) num2 = int(sys.argv[2]) main(num1, num2) except ValueError: print("Both arguments must be integers") sys.exit(1) else: print("Usage: python calc.py num1 num2") sys.exit(1) |
Conclusion
Congratulations! You have successfully learned how to execute a Python script with arguments using the command line and handling input within the script. This is a valuable skill when working on more complex projects or building applications to handle various inputs for different scenarios. Keep practicing, and happy coding!