Concepts / Handling Exceptions in Python

Handling Exceptions in Python

The sys module provides system-specific functionality and acts as an interface between Python and the operating system.

  • Programming

Why System Information Matters

A Python program sometimes needs information about the environment in which it is running. The sys module provides system-specific functionality and acts as an interface between Python and the operating system. Two especially useful parts of this module are sys.argv, which exposes command-line arguments, and sys.version_info, which provides Python version information.

system dataaccessible informationOperating systemcommand-line input andenvironmentsys modulesystem-specific interfacePython programreads argv and versioninformation
How does system information move between the operating system, the sys module, and a Python program?

Reading Command-Line Positions

sys.argv is a list containing the command-line arguments supplied when a script is run. Position 0 always contains the script name. User-provided arguments begin at position 1, so their positions depend on the order in which they appear on the command line.

next positionnext position0demo.py1hello2world
How do command-line arguments map to positions in the sys.argv list?

Mapping demo.py hello world

Determine the contents and positions of sys.argv when the script is run as python demo.py hello world.

Position 0: The first element is the script name, so sys.argv[0] is demo.py.

Position 1: The first user-provided argument is hello, so it appears at sys.argv[1].

Position 2: The second user-provided argument is world, so it appears at sys.argv[2].

List length: The list contains the script name plus two user-provided arguments, so len(sys.argv) is 3.

sys.argv contains ['demo.py', 'hello', 'world'], and its length is 3.

Tracing Different Invocations

The contents of sys.argv change according to what is typed at the command line. Running a script without additional arguments produces a list with only one element: the script name. Adding arguments adds more elements after position 0.

Command-line situationsys.argv contentsLength
No additional argumentsOne element containing the script name1
python demo.py hello world['demo.py', 'hello', 'world']3

The source describes how adding user-provided arguments changes sys.argv.

before accessposition is availableposition is absentNeed an argumentCheck list lengthlen(sys.argv)Use available valueAvoid invalid access
What check helps prevent an invalid access to a specific command-line position?

Check the length of sys.argv before accessing a specific index. This verifies that the position exists and helps you avoid errors caused by missing command-line arguments.

Inspecting Python Version Details

sys.version_info is a tuple containing Python version details. Its major version can be accessed with sys.version_info.major. Checking this value tells a program whether it is running Python 3, because the major version is 3 in that case.

fieldinspectsys.version_infoPython version tuplemajor3 in the source scenarioPython 3 checksys.version_info.major
Which part of sys.version_info can a program inspect to check whether Python 3 is running?

What do you think happens?

In the source scenario, a script is run without additional command-line arguments on Python 3.11.7. What should the script report about sys.argv and the major version?

  • sys.argv has one element, and the major version is 3
  • sys.argv has three elements, and the major version is 11
  • sys.argv is empty, and the major version is 7
Reveal answer

Answer: sys.argv has one element, and the major version is 3.

With no additional arguments, sys.argv contains only the script name. The source scenario reports Python 3.11.7, so sys.version_info.major is 3.

Version information is useful when diagnosing a program that behaves differently from what you expect. Inspect the major version first when the program depends on a particular Python version. The source scenario reports Python 3.11.7, but the important access pattern for the lesson is sys.version_info.major.

Diagnosing Input Problems

When a script does not behave as expected, inspect two sources of information: the Python version and the command-line inputs. First, use sys.version_info.major to check the major Python version. Next, inspect sys.argv and its length to determine whether the script name and expected user arguments are present. Finally, remember that the available arguments are strings and may need conversion before arithmetic.

startthenthenuse findingsUnexpected behaviorCheck major versionsys.version_info.majorInspect argumentssys.argv and its lengthCheck string valuesconvert when arithmetic isneededNarrow the problemversion or command-lineinput
What sequence of checks can distinguish a version issue from missing or unsuitable command-line input?
  • Treating sys.argv[0] as the first user-provided argument.

    sys.argv[0] always contains the script name.

    Fix: Look for user-provided arguments beginning at position 1.

  • Assuming a value in sys.argv is already a number.

    All values in sys.argv are strings.

    Fix: Convert the value to int or float when arithmetic is needed.

  • Accessing a specific position without checking the list length.

    The requested position may not exist.

    Fix: Check len(sys.argv) before accessing a specific index.

  • Confusing the major version with the complete version.

    The major field identifies the major version; in the source scenario it is 3.

    Fix: Use sys.version_info.major when checking whether Python 3 is running.

Practice the Checks

EASY

A script is run as python report.py 42. Determine the expected positions in sys.argv, the length of the list, and the type of the value supplied as the user argument. Then state which sys.version_info attribute should be inspected to check whether Python 3 is running.

Hints
  • Position 0 contains the script name.
  • The value 42 is still a string when it appears in sys.argv.
  • There are two list elements: the script name and one user-provided argument.

Checking report.py 42

Interpret the command-line input python report.py 42.

Position 0: sys.argv[0] contains report.py.

Position 1: sys.argv[1] contains the user-provided value 42, represented as a string.

Length: The list has two elements, so len(sys.argv) is 2.

Version check: Inspect sys.version_info.major to check whether the program is running Python 3.

The command supplies one user argument, stored at position 1 as a string; the version check uses sys.version_info.major.

Key Takeaways

  1. The sys module provides system-specific functionality and connects a Python program with the operating system.
  2. sys.argv is a list whose position 0 contains the script name and whose later positions contain user-provided arguments.
  3. All values in sys.argv are strings, so convert them to int or float when arithmetic is required.
  4. sys.version_info contains Python version details, and sys.version_info.major can be used to check for Python 3.
  5. Checking the version, the length of sys.argv, and the types of its values helps diagnose program input problems and avoid errors.

Key Takeaways

  • The sys module is an interface to system-specific functionality.
  • sys.argv maps the script name and command-line arguments to list positions.
  • Command-line values are strings and may require conversion before arithmetic.
  • sys.version_info.major provides the major Python version for version checks.
  • Length and version checks help identify missing inputs and environment-related problems.