The Simplest Introduction To Sys.Argv As A Way To Pass Arguments From Command Line
1 min readFeb 22, 2022
The concern is documenting an exemplary implementation of command-line arguments while keeping the code testable also from REPL or module (i.e. code editor). These are notes under the amazing course Core Python: Getting Started
- at the top of your file
import sys
module - at the bottom of your file, use the pattern to run script immediatelly if called from a shell (
if __name__ == "__main__":...
) - use
argv[<n>]
to refer to the first, second, and nth positional argument - the number must start from
1
not from0
for example:
# md2med.pyimport sys
def main(doc_name, file_to_publish):
# CODE ACCEPTING THE PARAMS HERE
#...
if __name__ == "__main__":
main(doc_name=sys.argv[1], file_to_publish=sys.argv[2])
5. when running this, pass the values into the terminal after the name of the script
>>> python md2med.py test-doc ./test-doc.md
1. ISSUE WITH INTGERS
- it is required to pass strings
TypeError
is thrown when working with passed number as an int
>>> python .\pv.py "com-snplow-sales-aws-prod1.collector.snplow.net" 5
TypeError: 'str' object cannot be interpreted as an integer
2. WHAT DOES ARGV MEAN ?
The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not).
- argv means argument vector
- in C, there is also argc, which is argument count