0% found this document useful (0 votes)
2 views7 pages

Batch 7 Python

The document explains the use of sys.argv in Python for handling command-line arguments, including examples of adding two numbers with error handling. It also discusses sys.path for module importing and its implications on maintainability. Additionally, it presents an extension task for creating a command-line script that performs operations based on flags, with structured error handling for various scenarios.

Uploaded by

hariikrishna5701
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views7 pages

Batch 7 Python

The document explains the use of sys.argv in Python for handling command-line arguments, including examples of adding two numbers with error handling. It also discusses sys.path for module importing and its implications on maintainability. Additionally, it presents an extension task for creating a command-line script that performs operations based on flags, with structured error handling for various scenarios.

Uploaded by

hariikrishna5701
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Solutions for Question

1 and Extension Task


Python Command-Line Arguments and Module Path

Date: May 20, 2025

Batch 7
K.SHIVANI (242FA05029)
G.MOHITH VENU REDDY (242FA05024)
MANOJ BHUDANIYA (242FA05042)
PANDAY THUFAN (242FA05051)
Understanding sys.argv
What is sys.argv? Argument Indexing
A list holding command-line arguments passed sys.argv[0] is the script name. Subsequent indexes
to a Python script. hold inputs.

Example Usage :
import sys

print("Script name:", sys.argv[0]) output


print("Number of arguments:", len(sys.argv)) Script name: script.py
print("Arguments:", sys.argv[1:]) Number of arguments: 3
Arguments: ['hello', '123']

Run from terminal:


python script.py hello 123
1(b). Program to add two values using sys.argv with error handling
Python Script:

Save this as add_args.py:

import sys

try:
TO RUN IN TERMINAL
if len(sys.argv) < 3: python add_args.py 10 20
raise ValueError("Two numbers must be provided.")

num1 = float(sys.argv[1]) OUTPUT :


num2 = float(sys.argv[2]) Sum: 30.0
print("Sum:", num1 + num2)

except ValueError as ve:


If arguments are missing:
print("ValueError:", ve) ValueError: Two numbers must be provided.
except IndexError:
print("Error: Not enough command-line arguments.")
except Exception as e:
print("Unexpected error:", e)
1(c): Effect of sys.path on Module Importing
What is sys.path?

•sys.path is a list of strings that specifies the search path for Python modules.

•It is used by the interpreter to locate the modules during import.

Modifying sys.path:
You can manually add custom directories to sys.path to import modules from non-standard locations .

import sys
sys.path.append('/home/user/my_modules') # Add custom path

import mymath # Assuming mymath.py is in the specified folder


mymath.greet()
Impact on Maintainability:
✅ Pros:

•Enables importing modules from custom or external directories.

•Useful in development environments.

❌ Cons:

•Can lead to ambiguous imports and debugging issues.

•Not recommended for large-scale applications.

•Better alternatives include virtual environments or dependency managers like pip.


Extension Task
A: Enhanced Command-line Script With Flags
Objective:
Use sys.argv to accept multiple numeric arguments and perform operations like sum, average, or max based on a flag .
import sys

def show_help():
print("Usage: python script.py --sum|--avg|--max num1 num2 ...")
print("Example: python script.py --avg 10 20 30") EXAMPLE RUN :
python script.py --max 3 15 9
try:
if len(sys.argv) < 3:
raise ValueError("Not enough arguments.")

flag = sys.argv[1]
numbers = list(map(float, sys.argv[2:]))

if flag == "--sum": OUTPUT


print("Sum =", sum(numbers))
elif flag == "--avg": Maximum = 15.0
print("Average =", sum(numbers) / len(numbers))
elif flag == "--max":
print("Maximum =", max(numbers))
elif flag == "--help":
show_help()
else:
raise ValueError("Unknown flag: " + flag)

except ValueError as ve:


print("Error:", ve)
except Exception as e:
print("Unexpected error:", e)E
b: Help and Error Handling
Provide a --help flag and implement structured exception handling for:
 Invalid flags
 Missing values
 Wrong data types

Example Error Scenarios:

1) 3)
python script.py --sum abc python script.py --help
OUTPUT:
Error: could not convert string to float: 'abc' OUTPUT:
Usage: python script.py --sum|--avg|--max num1 num2 ...
2)
python script.py
OUTPUT
Error: Not enough arguments.

You might also like