7.3 Command Line Arguments in Python
Moving on to the Python example and running the new tests3.
1cd ~/python 2poetry run pytest --tb=no -v
Again, these tests will fail because we have new requirements, hence new tests, which require new code.
1============================= test session starts ============================== 2platform linux -- Python 3.9.2, pytest-7.1.2, pluggy-1.0.0 -- /usr/bin/python3 3cachedir: .pytest_cache 4rootdir: /home/vagrant/python 5plugins: bdd-6.0.1 6collected 2 items 7 8tests/test_convert.py::test_welcome_message[-Hello !\n] FAILED [ 50%] 9tests/test_convert.py::test_welcome_message[Mark-Hello Mark!\n] FAILED [100%] 10 11=========================== short test summary info ============================ 12FAILED tests/test_convert.py::test_welcome_message[-Hello !\n] - AssertionErr... 13FAILED tests/test_convert.py::test_welcome_message[Mark-Hello Mark!\n] - Asse... 14============================== 2 failed in 1.37s ===============================
We can fix these failing tests by changing the program to the following.
1import sys 2 3name = sys.argv[1] 4greeting_message = f"Hello {name}!" 5print(greeting_message)
Python deals with command line arguments a bit differently to Bash and Lua. Rather than built in special variables like $1
and argv
, Python relies on a package (a library of code4) that is loaded into the script using the
import sys
directive on line 1. Once the sys package is loaded we have access to sys.argv
which works in a similar way to Lua’s argv
; each command line argument is placed into the corresponding sys.argv
entry (so the first command line argument is placed in sys.argv[1]
). As with the other versions of this program we set create the name variable to give this first argument a more readable name.
Line 4 assigns the greeting string to greeting_message. This is a Python ‘format’ string, which work in a similar way to Bash strings in that the variable in {}
is expanded into the string5.
3I use the --tb=no -v flags to produce more compact output for this book. If you want to leave these flags off the result will be the same but with more verbose output.
4We discuss these packages when we cover organising code.
5This is doing Python format strings a disservice, they are more powerful than this suggests but for now this simplification will serve.