Python

Python [Python ] Python

Python getopt

$ python test.py arg1 arg2 arg3

Python sys sys.argv

  • sys.argv

  • len(sys.argv)

sys.argv[0]

test.py

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import sys

print ':', len(sys.argv), ''
print ':', str(sys.argv)

$ python test.py arg1 arg2 arg3
: 4 
: ['test.py', 'arg1', 'arg2', 'arg3']

getopt

getoptsys.argv - --

getopt.getopt

getopt.getopt

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

  • args:

  • options : options :

  • long_options : long_options =

  • : (option, value) - --

getopt.gnu_getopt


Exception getopt.GetoptError

msg opt

usage: test.py -i <inputfile> -o <outputfile>

test.py

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import sys, getopt

def main(argv):
   inputfile = ''
   outputfile = ''
   try:
      opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
   except getopt.GetoptError:
      print 'test.py -i <inputfile> -o <outputfile>'
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print 'test.py -i <inputfile> -o <outputfile>'
         sys.exit()
      elif opt in ("-i", "--ifile"):
         inputfile = arg
      elif opt in ("-o", "--ofile"):
         outputfile = arg
   print '', inputfile
   print '', outputfile

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

$ python test.py -h
usage: test.py -i <inputfile> -o <outputfile>

$ python test.py -i inputfile -o outputfile
 inputfile
 outputfile

Python [Python ] Python