Python排序/反向与argparse无法正常工作

时间:2014-09-30 07:22:55

标签: python sorting argparse

任务是命令行中的简单排序/反向字符串。我们将非常感谢正确方向上的一点。

#!/usr/bin/python 
# Sort and unsort using python
#The purpose of this program is to take strings as command line arguments and sort
#invoke by: python filename.py string string string 
# -r would should output reverse order sort

import sys  #for the command line strings to be sorted
import argparse  #this is a good getopt alternative 

#these lines are used to create the reverse switch
parser = argparse.ArgumentParser()
parser.add_argument('-r','--reverse', help='reverse flag', action='store_true')

#variables to control the switch and command line strings    
args = parser.parse_args()
strings = sys.argv

def main():  #main 

  if len(sys.argv) < 2:   # use to test in the user has inputted enough words
    print "error, you do not have enough words to sort"
    sys.exit()

  if args.reverse:  # this is the reverse sort statement
   strings.pop(0)
   strings.sort() 
   strings.reverse()
   print strings

  if not any(vars(args).values()):  # here is the normal sort statement 
   strings.pop(0)
   strings.sort()     
   print strings

if __name__== '__main__':  #if statement for the main method
   main() here

我在python 2.7

中一直遇到无法识别的参数错误

1 个答案:

答案 0 :(得分:2)

你需要告诉argparse要对这些词进行排序; sys.argv包含未解析的参数列表(包括程序名称):

parser = argparse.ArgumentParser()
parser.add_argument('-r','--reverse', help='reverse flag', action='store_true')
parser.add_argument('words', nargs='+', help='words to sort')

nargs='+'参数告诉ArgumentParser期望至少有一个参数。

解析后,args.words是您的字符串列表。

关于样式的注释:而不是总是解析参数,只解析命令行参数是if __name__ == '__main__':保护,并将结果直接传递给函数而不是使用全局变量:

parser = argparse.ArgumentParser()
parser.add_argument('-r','--reverse', help='reverse flag', action='store_true')
parser.add_argument('words', nargs='+', help='words to sort')

def main(strings, reverse=False):
    # do the sorting work

if __name__ == '__main__':
    args = parser.parse_args()
    if len(args.words) < 2:
        parser.error('you do not have enough words to sort')
    main(args.words, args.reverse)