How To Execute Python Script With Arguments

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:

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:

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:

Now, if you try to pass a non-integer argument or divide by zero, the script will handle these errors correctly.

Both arguments must be integers
Sum: 10
Difference: 10
Product: 0
Cannot divide by zero

Full Code

Here is the final version of the calc.py script:

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!