Command-line arguments¶
Learning outcomes
- Read the official Python documentation about
sys.argv - Read How to Think Like a Computer Scientist: Learning with Python 3
- Can read the command-line arguments
- Can run a Python script with command-line arguments
For teachers
Teaching goals are:
- Learners have used sys.args
- Learners have run a Python script with command-line arguments
Lesson plan:
- 5 mins: prior knowledge
- 5 mins: presentation
- 15 mins: challenge
- 5 mins: feedback
Prior:
- What are command-line arguments?
- What is meant with 'a command-line interface'?
- Why use command-line arguments?
Overview¶
Sometime, also programs need input, for example the name of the input file and the name of a results file:
Sometime you need to get 'stuff to work', for example, code written by someone else. In this session, we practice this, going through the problems and errors that occur when you want to 'just want to run the stupid code'.
Exercises¶
Exercise 1: Read the command-line arguments¶
Read
the official Python documentation about sys.argv.
Create a script called read_argv.py with the following content:
Run the Python script as shown below. What does it print?
Run the Python script as shown below. What does it print?
Run the Python script as shown below. What does it print?
Run the Python script as shown below. What does it print?
Exercise 2: Read a command-line argument¶
sys.argv is a list. Here we use this list
Read the following sections of How to Think Like a Computer Scientist: Learning with Python 3:
11. Lists11.1. List values11.2. Accessing elements
Modify the script in such a way that the script will only show the first command-line argument.
For example, running the script like this:
it should show hello.
Answer
A possible implementation is this:
Some comments:
print(args[0])prints the name of the script- the script does not check if the user supplies command-line arguments
Exercise 3: Work with a command-line argument¶
Read the following sections of How to Think Like a Computer Scientist: Learning with Python 3:
- 8.7. String comparison
Now, we make the script produce different output.
If the script is run like this:
it should show Hello human!.
If the script is run like this:
it should show Sad to see you go human!.
Write the script to do that.
Answer
A possible implementation is this:
import sys
args = sys.argv
word = args[1]
if word == 'hello':
print('Hello human!')
if word == 'bye':
print('Sad to see you go human!')
Some comments:
print(args[0])prints the name of the script- the script does not check if the user supplies command-line arguments
- instead of using two
ifstatements (which is good enough for this exercise), anelifcould be used in the second conditional: it would be considered better, because if the word ishello, then there is no need anymore to check if it isbye