Accepting command line arguments

That last change actually breaks our main() since it's not passing the new url argument. When running our module as a standalone program, we'll need to accept the URL as a command line argument. Access to command line arguments in Python is through an attribute of the sys module called argv which is a list of strings. To use it we must first import the sys module at the top of our program:

import sys

We then get the second argument (with an index of one) from the list:

def main():
url = sys.argv[1]
words = fetch_words(url)
print_items(words)

And of course this works as expected:

$ python3 words.py http://sixty-north.com/c/t.txt
It
was
the
best
of
times

This looks fine until we realize that we can't usefully test main() any longer from the REPL because it refers to sys.argv[1] which is unlikely to have a useful value in that environment:

$ python3
Python 3.5.0 (default, Nov 3 2015, 13:17:02)
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from words import *
>>> main()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/sixtynorth/projects/sixty-north/the-python-
apprentice/manuscript/code/pyfund/words.py", line 21, in main

url = sys.argv[1]
IndexError: list index out of range
>>>

The solution is to allow the argument list to be passed as a formal argument to the main() function, using sys.argv as the actual parameter in the if __name__ == '__main__' block:

def main(url):
words = fetch_words(url)
print_items(words)

if __name__ == '__main__':
main(sys.argv[1])

Testing from the REPL again, we can see that everything works as expected:

>>> from words import *
>>> main("http://sixty-north.com/c/t.txt")
It
was
the
best
of
times

Python is a great tool for developing command line tools, and you'll likely find that you need to handle command line arguments for many situations. For more sophisticated command line processing we recommend you look at the Python Standard Library argparse module or the inspired third-party docopt module.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset