Lab 06 - Command Line Arguments

Due by 11:59pm on 2024-01-30.

Starter Files

Download lab06.zip. Inside the archive, you will find starter files for the questions in this lab.

Topics

Intro to Command Line Arguments

Let's say that we are coding a program that calculates pay given rate and hours:

def calculate_pay(rate, hours):
return rate * hours

rate = 5.5
hours = 45

print(calculate_pay(rate, hours)) # 247.5

Notice that if we ever want to calculate pay for multiple people using or program, we have to manually go into our code and change the rate and hours variables we call calculate_pay with. There is a better way.

Instead of manually going into our code and executing our code in the command line/terminal, we can merge the two steps by allowing our code to take additional command line arguments within the terminal. In this case, 5.5 and 45 are command line arguments:

python3 program.py 5.5 45
247.5

To do this in our code, we have to import the sys library. To have access to a list of argument values, we use sys.argv. For example, if we execute python3 example.py hi im a command line argument 1 in the command line with the following code:

import sys
print(sys.argv)

It would print ['example.py', 'hi', 'im', 'a', 'command', 'line', 'argument', '1']

Notice that the first command line argument is the python file's name 'example.py' and that the '1' was represented as a string. If we are taking numbers as command line arguments, we have to convert them from strings to actual numbers using the int() or float() functions.

We can edit our code to look something more like this to make it more versatile:

def calculate_pay(rate, hours):
return rate * hours

rate = float(sys.argv[1])
hours = float(sys.argv[2])

print(calculate_pay(rate, hours)) # 247.5

Recall that the float() function converts an integer or string to a float -- a decimal number.

Discuss

Why would it be helpful to have your program accept command line arguments?

Consider the situation with the calculate_pay program.

What if I wanted to apply any filter to any image without manually changing the code?

Setting Command Line Arguments in Your IDE

Sometimes you might not want to run your code in the terminal, but instead want to run it from the IDE (with the Run button) but using command line arguments. Your IDE likely supports this feature. The following will show you how to set it up in VS Code and Pycharm.

VS Code

Navigate to the python file you want to work with. Under Run select Add Configurations.... Select Python File

vs_code_1 vs_code_2

A launch.json file should have been created. Within the configurations key-value pairs, add "args": ["arg1", "<arg2"]. Remember to put a comma after the previous key-value pair.

vs_code_3

Now navigate back to your python file, and under the Run tab select Run Without Debugging

vs_code_4

PyCharm

Near the top-right corner, click on the box with the name of your python file. Then click Edit Configurations...:

pycharm_command_line_1

A new window should have opened. You might see Add New Configurations text; if so, click it and select Python File. Now input your command line arguments into the parameters box:

pycharm_command_line_2

Now click Apply and OK near the bottom-right corner of the new window. You should be able to run your program with command line arguments when you click the Run button

Required Questions

Note: Like the previous lab, some of the functionality you write here will be used in Project 1. Make every effort to complete these problems in Lab where you have help from TAs and others students to save you work on the project.

Q1: WWPD: Command Line Arguments

If you ever unsure or stuck on what Python will display, run the code yourself and see what Python displays!

If we have a python file called program.py that contains these lines of code:

import sys
print(sys.argv)

What would program.py print if we ran it in the terminal like the following?

python3 program.py
_____
python3 program.py cs is cool 1
_____
python3 program.py cs_is_cool 1
_____

If we have a python file called cs_is_cool.py that contains these lines of code:

import sys
print(sys.argv[1:])

What would cs_is_cool.py print if we ran it in the terminal like the following?

python3 cs_is_cool.py . /
_____
python3 cs_is_cool.py . / ;
_____
python3 cs_is_cool.py . / ';'
_____
python3 cs_is_cool.py 'wow this is cool!'
_____

As you can see, some characters have special meaning in the terminal. You can surround those characters in quote to ensure those characters are literally interpreted as themselves.

Q2: Printing Arguments

Modify the provided lab06.py file so that it reads in the command line arguments and passes them into a function called print_args, which prints them, one argument per line.

For example, if we run python3 lab06.py 1 2 3 4, it should print:

lab06.py
1
2
3
4

Q3: Flags

Add a function that checks to see, given a list of arguments, if the second argument is one of -p, -i, or -h and returns True if it is; otherwise, it returns False.

Add a second function called flags that takes in a list of arguments. If there is a valid flag in the proper spot, flags should do the following based on the flag:

  • -p - print out all the command line arguments after the -p (on separate lines)
  • -i - print "Hello World"
  • -h - prints out a help command with the following information
    Valid flags:
    -p : prints out all the command line arguments after the -p
    -i : prints "Hello World"
    -h : prints out a help command
    

Your main program should then do the following

  • If there is a valid flag, call flags
  • Else, call print_args

For example:

> python3 lab06.py -i
Hello World

> python3 lab06.py foo bar baz
lab06.py
foo
bar
baz

> python3 lab06.py -p my 3 arguments
my
3
arguments

> python3 lab06.py -h
Valid flags:
-p : prints out all the command line arguments after the -p
-i : prints "Hello World"
-h : prints out a help command

Tip: You can use print_args in the case of the -p option. When calling print_args, provide the command line arguments list where the first item has been stripped off.

Q4: File IO

Implement two additional flags, -w and -r, to your program.

If the flag is -w, write to a file specified in the next argument. The arguments that follow after the filename will be what you want to write to the file, one argument per line.

For example, running

python3 lab06.py -w output.txt Hello World

should give you a file output.txt with

Hello
World

If the user does not provide any content when trying to write, print No Content Provided and do not write to the file. (You can do this by checking the length of the command line arguments list.)

Note: Do not worry about the extra empty line created when writing to the file

If the flag is -r read from the file specified in the following arguments and print out each line in the file. For example, using output.txt from the previous example:

python3 lab06.py -r output.txt
Hello
World

Submit

Submit the lab06.py file on Canvas to Gradescope in the window on the assignment page.


© 2024 Brigham Young University, All Rights Reserved