官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 信丰县| 洮南市| 班玛县| 昆明市| 霍州市| 老河口市| 新巴尔虎右旗| 伊吾县| 昆山市| 巨鹿县| 衡水市| 宣化县| 麦盖提县| 台北县| 禄丰县| 炎陵县| 汉源县| 安陆市| 柳州市| 江津市| 巫溪县| 桐庐县| 调兵山市| 丰宁| 昭觉县| 开平市| 五寨县| 武冈市| 嘉祥县| 广德县| 云浮市| 乌兰察布市| 光泽县| 洪洞县| 抚州市| 崇左市| 广宗县| 永顺县| 克什克腾旗| 昭通市| 穆棱市|