乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      getopt在Python中的使用(轉(zhuǎn))

       panhoy 2015-09-08

      在運行程序時,可能需要根據(jù)不同的條件,輸入不同的命令行選項來實現(xiàn)不同的功能。目前有短選項長選項兩種格式。短選項格式為"-"加上單個字母選項;長選項為"--"加上一個單詞。長格式是在Linux下引入的。許多Linux程序都支持這兩種格式。在Python中提供了getopt模塊很好的實現(xiàn)了對這兩種用法的支持,而且使用簡單。


      取得命令行參數(shù)
        在使用之前,首先要取得命令行參數(shù)。使用sys模塊可以得到命令行參數(shù)。
      import sys
      print sys.argv

        然后在命令行下敲入任意的參數(shù),如:
      python get.py -o t --help cmd file1 file2

        結(jié)果為:
      ['get.py', '-o', 't', '--help', 'cmd', 'file1', 'file2']

        可見,所有命令行參數(shù)以空格為分隔符,都保存在了sys.argv列表中。其中第1個為腳本的文件名。

      選項的寫法要求
        對于短格式,"-"號后面要緊跟一個選項字母。如果還有此選項的附加參數(shù),可以用空格分開,也可以不分開。長度任意,可以用引號。如以下是正確的:
      -o
      -oa
      -obbbb
      -o bbbb
      -o "a b"
        對于長格式,"--"號后面要跟一個單詞。如果還有些選項的附加參數(shù),后面要緊跟"=",再加上參數(shù)。"="號前后不能有空格。如以下是正確的:

      --help=file1

        而這些是不正確的:
      -- help=file1
      --help =file1
      --help = file1
      --help= file1

      如何用getopt進行分析
        使用getopt模塊分析命令行參數(shù)大體上分為三個步驟:

      1.導入getopt, sys模塊
      2.分析命令行參數(shù)
      3.處理結(jié)果

        第一步很簡單,只需要:
      import getopt, sys

        第二步處理方法如下(以Python手冊上的例子為例):
      try:
          opts, args = getopt.getopt(sys.argv[1:], "ho:", ["help", "output="])
      except getopt.GetoptError:
          # print help information and exit:

      1.
      處理所使用的函數(shù)叫getopt(),因為是直接使用import導入的getopt模塊,所以要加上限定getopt才可以。
      2. 使用sys.argv[1:]過濾掉第一個參數(shù)(它是執(zhí)行腳本的名字,不應算作參數(shù)的一部分)。
      3. 使用短格式分析串"ho:"。當一個選項只是表示開關(guān)狀態(tài)時,即后面不帶附加參數(shù)時,在分析串中寫入選項字符。當選項后面是帶一個附加參數(shù)時,在分析串中寫入選項字符同時后面加一個":"號。所以"ho:"就表示"h"是一個開關(guān)選項;"o:"則表示后面應該帶一個參數(shù)。
      4. 使用長格式分析串列表:["help", "output="]。長格式串也可以有開關(guān)狀態(tài),即后面不跟"="號。如果跟一個等號則表示后面還應有一個參數(shù)。這個長格式表示"help"是一個開關(guān)選項;"output="則表示后面應該帶一個參數(shù)。
      5. 調(diào)用getopt函數(shù)。函數(shù)返回兩個列表:opts和args。opts為分析出的格式信息。args為不屬于格式信息的剩余的命令行參數(shù)。opts是一個兩元組的列表。每個元素為:(選項串,附加參數(shù))。如果沒有附加參數(shù)則為空串''。
      6. 整個過程使用異常來包含,這樣當分析出錯時,就可以打印出使用信息來通知用戶如何使用這個程序。

        如上面解釋的一個命令行例子為:
      '-h -o file --help --output=out file1 file2'

        在分析完成后,opts應該是:
      [('-h', ''), ('-o', 'file'), ('--help', ''), ('--output', 'out')]

        而args則為:
      ['file1', 'file2']

        第三步主要是對分析出的參數(shù)進行判斷是否存在,然后再進一步處理。主要的處理模式為:
      for o, a in opts:
          if o in ("-h", "--help"):
              usage()
              sys.exit()
          if o in ("-o", "--output"):
              output = a

        使用一個循環(huán),每次從opts中取出一個兩元組,賦給兩個變量。o保存選項參數(shù),a為附加參數(shù)。接著對取出的選項參數(shù)進行處理。(例子也采用手冊的例子)


       

      15.6. getopt — C-style parser for command line options

      Note

      The getopt module is a parser for command line options whose API is designed to be familiar to users of the C getopt() function. Users who are unfamiliar with the C getopt() function or who would like to write less code and get better help and error messages should consider using the argparse module instead.

      This module helps scripts to parse the command line arguments in sys.argv. It supports the same conventions as the Unix getopt() function (including the special meanings of arguments of the form ‘-‘ and ‘--‘). Long options similar to those supported by GNU software may be used as well via an optional third argument.

      A more convenient, flexible, and powerful alternative is the optparse module.

      This module provides two functions and an exception:

      getopt.getopt(args, options[, long_options])

      Parses command line options and parameter list. args is the argument list to be parsed, without the leading reference to the running program. Typically, this means sys.argv[1:]. options is the string of option letters that the script wants to recognize, with options that require an argument followed by a colon (':'; i.e., the same format that Unix getopt() uses).

      Note

      Unlike GNU getopt(), after a non-option argument, all further arguments are considered also non-options. This is similar to the way non-GNU Unix systems work.

      long_options, if specified, must be a list of strings with the names of the long options which should be supported. The leading '--' characters should not be included in the option name. Long options which require an argument should be followed by an equal sign ('='). Optional arguments are not supported. To accept only long options, options should be an empty string. Long options on the command line can be recognized so long as they provide a prefix of the option name that matches exactly one of the accepted options. For example, if long_options is ['foo', 'frob'], the option --fo will match as --foo, but --f will not match uniquely, so GetoptError will be raised.

      The return value consists of two elements: the first is a list of (option, value) pairs; the second is the list of program arguments left after the option list was stripped (this is a trailing slice of args). Each option-and-value pair returned has the option as its first element, prefixed with a hyphen for short options (e.g., '-x') or two hyphens for long options (e.g., '--long-option'), and the option argument as its second element, or an empty string if the option has no argument. The options occur in the list in the same order in which they were found, thus allowing multiple occurrences. Long and short options may be mixed.

      getopt.gnu_getopt(args, options[, long_options])

      This function works like getopt(), except that GNU style scanning mode is used by default. This means that option and non-option arguments may be intermixed. The getopt() function stops processing options as soon as a non-option argument is encountered.

      If the first character of the option string is ‘+’, or if the environment variable POSIXLY_CORRECT is set, then option processing stops as soon as a non-option argument is encountered.

      New in version 2.3.

      exception getopt.GetoptError

      This is raised when an unrecognized option is found in the argument list or when an option requiring an argument is given none. The argument to the exception is a string indicating the cause of the error. For long options, an argument given to an option which does not require one will also cause this exception to be raised. The attributes msg and opt give the error message and related option; if there is no specific option to which the exception relates, opt is an empty string.

      Changed in version 1.6: Introduced GetoptError as a synonym for error.

      exception getopt.error
      Alias for GetoptError; for backward compatibility.

      An example using only Unix style options:

      >>> import getopt
      >>> args = '-a -b -cfoo -d bar a1 a2'.split()
      >>> args
      ['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
      >>> optlist, args = getopt.getopt(args, 'abc:d:')
      >>> optlist
      [('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
      >>> args
      ['a1', 'a2']
      

      Using long option names is equally easy:

      >>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
      >>> args = s.split()
      >>> args
      ['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
      >>> optlist, args = getopt.getopt(args, 'x', [
      ...     'condition=', 'output-file=', 'testing'])
      >>> optlist
      [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
      >>> args
      ['a1', 'a2']
      

      In a script, typical usage is something like this:

      import getopt, sys
      
      def main():
          try:
              opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
          except getopt.GetoptError, err:
              # print help information and exit:
              print str(err) # will print something like "option -a not recognized"
              usage()
              sys.exit(2)
          output = None
          verbose = False
          for o, a in opts:
              if o == "-v":
                  verbose = True
              elif o in ("-h", "--help"):
                  usage()
                  sys.exit()
              elif o in ("-o", "--output"):
                  output = a
              else:
                  assert False, "unhandled option"
          # ...
      
      if __name__ == "__main__":
          main()
      

      Note that an equivalent command line interface could be produced with less code and more informative help and error messages by using the argparse module:

      import argparse
      
      if __name__ == '__main__':
          parser = argparse.ArgumentParser()
          parser.add_argument('-o', '--output')
          parser.add_argument('-v', dest='verbose', action='store_true')
          args = parser.parse_args()
          # ... do something with args.output ...
          # ... do something with args.verbose ..
      

        本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
        轉(zhuǎn)藏 分享 獻花(0

        0條評論

        發(fā)表

        請遵守用戶 評論公約

        類似文章 更多