Overview

Introduction

Welcome to the Reading Command-Line Arguments Practice Lab. In this module, you will be provided with the instructions and devices needed to develop your hands-on skills.

Learning Outcomes

In this module, you will complete the following exercise:

  • Exercise 1 - Processing Command-Line Arguments

After completing this lab, you will be able to:

  • Use command-line arguments in a Python program

Exam Objectives

The following exam objectives are covered in this lab:

  • 3.2 Construct and analyze code segments that perform console input and output operations

Lab Duration

It will take approximately 20 minutes to complete this lab.

Exercise 1 - Processing Command-Line Arguments

You already know that the input() function helps you to read data at runtime. You also know that this function always returns a string. What if you want to pass arguments to your program at runtime? Python allows you to start a program with additional arguments.

For example,

program.py arg1 arg2 arg3

Here, program.py, arg1, arg2, and arg3 are command-line arguments.

You can get access to the command-line parameters using the built-in sys module.

Once you import the sys module, it provides access to any command-line arguments via the sys.argv. Here are a few important things about sys.argv:

  • sys.argv is an array holding the command-line arguments of a program. Remember that this array starts at [0], not [1].
  • The first argument, sys.argv[0], is always the name of the Python program; for example, program.py in the above code.
  • sys.argv[1] is the first command-line argument you pass to the program. In the above code, it is arg1. Likewise, sys.argv[2] is arg2 and sys.argv[3] is arg3.
  • len(sys.argv) is the number of command-line arguments.

You can also pass complete files as arguments. For example, the following code will pass the hello.txt file as a command-line argument:

program.py hello.txt

Once you pass a file (hello.txt, in this case) as an argument, you can perform various operations on the file as per the statements included in the program file (program.py, in this case).

In this exercise, you will learn to write a program to read the file given as a command-line argument and print the number of lines, words, and characters in the file.

Learning Outcomes

After completing this exercise, you will be able to:

  • Use command-line arguments in a Python program

Comprehensive Learning

See the full benefits of our immersive learning experience with interactive courses and guided career paths.