What are Command line arguments?
Command line arguments are values provided to a program when it is executed in the terminal or command prompt. They allow users to pass input dynamically, customizing the behavior of the program.
Command line arguments in Python
Here's a basic overview of command line arguments in Python:
The
sys
module provides access to command line arguments through theargv
attribute.In Python, the
sys.argv
list is commonly used to access command line arguments.sys.argv
is a list where the first element (sys.argv[0]
) is the script name, and the subsequent elements are the command line arguments.Example,
import sys
# Check if the correct number of arguments is provided
if len(sys.argv) != 3:
print("Usage: python script.py <number1> <number2>")
sys.exit(1) # Exit with an error code
# Extracting command line arguments
number1 = float(sys.argv[1])
number2 = float(sys.argv[2])
# Performing the addition
result = number1 + number2
# Displaying the result
print(f"The sum of {number1} and {number2} is: {result}")
Output,
python addition.py 5 10
15
Here is a more simple example,
import sys
# Accessing script name
script_name = sys.argv[0]
# Accessing command line arguments
arguments = sys.argv[1:]
print("Script Name:", script_name)
print("Command Line Arguments:", arguments)
NOTE: Command line arguments are passed as strings, and you may need to convert them to the desired data types using functions like int()
or float()
.
Calculator example
# file name - calc.py
import sys
def addition(num1, num2):
add = num1 + num2
return add
def subtraction(num1, num2):
sub = num1 - num2
return sub
num1 = float(sys.argv[1])
operation = sys.argv[2]
num2 = float(sys.argv[3])
if operation == "add":
result = addition(num1, num2)
print(result)
Output,
python calc.py 5.3 add 7.5
12.8
What are Environment Variables?
Environment variables are global system variables that store configuration settings, paths, or other information accessible to all processes running on a computer.
Environment variables in Python
In Python, the os
module is commonly used to interact with environment variables.
The os.environ
dictionary contains the environment variables, and you can get or set their values using the get()
and putenv()
functions.
Here's a simple example:
import os
# Get the value of an environment variable
username = os.environ.get('USERNAME')
print(f"Username: {username}")
# Set a new environment variable
os.environ['MY_VARIABLE'] = 'my_value'
print("MY_VARIABLE:", os.environ.get('MY_VARIABLE'))
In place of os.environ.get()
we can also use os.getenv()
. Both of them gives the same result.
Here is an example,
import os
print(os.environ.get("USERPROFILE"))
print(os.getenv("USERPROFILE"))
# Output
C:\Users\Me
C:\Users\Me
What's next?
In the next article in this blog series, we will look into operators in python.
Stay tuned.