Linux Journal Python练习

时间:2019-01-22 17:44:27

标签: linux python-3.x

作为Python练习的一部分,我正在阅读《 Linux Journal》上的这篇文章。到目前为止,它并不像我希望的那样直接。例如,其中一个清单的代码是:

#! /usr/local/bin/python
import sys, getopt, string
    def help_message():
        print '''options.py -- uses getopt to recognize options
        Options: -h      -- displays this help message
        -a      -- expects an argument
        --file= -- expects an argument
        --view  -- doesn't necessarily expect an argument
        --version -- displays Python version'''
     sys.exit(0)
try:
    options, xarguments = getopt.getopt(sys.argv[1:],
    'ha', ['file=', '--view', 'version'])
except getopt.error:
    print 'Error: You tried to use an unknown option or the
    argument for an option that requires it was missing. Try
    `options.py -h\' for more information.'
        sys.exit(0)
for a in options[:]:
    if a[0] == '-h':
        help_message()
for a in options[:]:
    if a[0] == '-a' and a[1] != '':
        print a[0]+' = '+a[1]
        options.remove(a)
        break
    elif a[0] == '-a' and a[1] == '':
        print '-a expects an argument'
        sys.exit(0)
for a in options[:]:
    if a[0] == '--file' and a[1] != '':
        print a[0]+' = '+a[1]
        options.remove(a)
        break
    elif a[0] == '--file' and a[1] == '':
        print '--file expects an argument'
        sys.exit(0)
for a in options[:]:
    if a[0] == '--view' and a[1] != '':
        print a[0]+' = '+a[1]
        options.remove(a)
        break
    elif a[0] == '--view' and a[1] == '':
        print '--view doesn\'t necessarily expects an argument...'
        options.remove(a)
        sys.exit(0)
for a in options[:]:
    if a[0] == '--version':
        print 'options version 0.0.001'
        sys.exit(0)
for a in options[:]:
    if a[0] == '--python-version':
        print 'Python '+sys.version
        sys.exit(0)

我了解help_message函数。代码不正确时,我不知道发生了什么:

try:
    options, xarguments = getopt.getopt(sys.argv[1:], 
    'ha', ['file=', '--view', 'version'])

在我看来,变量选项和xarguments被分配了getopt模块和方法对提供给它们的信息所做的工作。但我也不太了解其格式。如果我已正确阅读文档说明以及什么

,sys.argv [1:]将为''或'-c'
'ha', ['file=', '--view', 'version']) 

除非被分配了这些参数的值,并且我不理解为什么它们出现在[]中,否则它应该这样做。

我不明白的另一件事是

for a in options[:]:
    if a[0] == '-h':
        help_message()

以及类似的编码行。在我看来,[0]将是“-”,而[1]将是“ h”。编码器如何在一个索引位置包含“ -h”?他分几行这样做。请原谅我的天真,我读过一本关于Python基础知识的书,但没有意识到实现看起来如此复杂。我正在努力提高对代码的阅读和理解。

0 个答案:

没有答案
相关问题