Discuz! BBS

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 836|回复: 0

有关Python获取用户输入选项

[复制链接]

255

主题

364

帖子

2438

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
2438
发表于 2023-7-12 06:23:39 | 显示全部楼层 |阅读模式
还是上代码吧:
  1. import sys
  2. #====================
  3. def main(argv):
  4.     #debug:
  5.     print('Len(argv)=' + str(len(argv)) + '; argv[0]=' + argv[0])
  6.     if len(argv) < 3:
  7.         if len(argv) == 1 :
  8.             print("Lack arguments. Not run. Notice: Place the data-file in /home/cuibe/work/replace/, and invoke it explicitly.")
  9.             return -1
  10.         elif len(argv) == 2 and (argv[1] == '--help' or argv[1] == '-h'):
  11.             print("\nReplacer.py [-t|--exec|-h|--help] datafile \n-h --help   get the help notice.\n--exec   do real copy\n-t   do not real copy,test and verbos it only. ")
  12.             return -1
  13.         elif len(argv) == 2:
  14.             print("Bad or lack option. Please reference help to give correct one.")
  15.             return -1
  16.     else:
  17.         if argv[1] == '--exec':
  18.             notTest = True
  19.         elif argv[1] == '-t':
  20.             notTest = False
  21.         else:
  22.             print("You provides wrong option.Try again.")
  23.             return -1
  24.     try:
  25.         file = str(argv[2])
  26.         filePath = "./" + file

  27.         define_outfile = False
  28.         if len(argv) > 3 :
  29.             outfile = './' + str(argv[3])  # argv[3] must have if len > 3.
  30.             define_outfile = True
  31.         #debug:
  32.         print(filePath, outfile)  # may raise exception : reference before assignment
  33.         print(argv)
  34.     except Exception, err:
  35.         print('Make path error: ' + str(Exception) + str(err))

  36.     result = -1
  37.     try:
  38.         if define_outfile == True:
  39.             result = dosomething(, notTest, outfile)
  40.         else:
  41.             result = printAttr(entities, notTest)
  42.     except Exception, err:
  43.         print('Changing error: ' + str(Exception) + str(err))
  44.         traceback.print_exc()
  45.    
  46.     print("------------------------------")
  47.     if result == 0:
  48.         print("Done.")
  49.         return 0
  50.     else:
  51.         print("Proceed with error, check logs.")
  52.         return -1


  53. if __name__ == '__main__' : main(sys.argv)
复制代码

另一种代码:
  1. #====================
  2. def main(argv):
  3.         #debug:
  4.         #print('Len(argv)=' + str(len(argv)) + '; argv[0]=' + argv[0], end='')
  5.         #end
  6.         arg_dict = dict()
  7.         arg_dict["k_words"] = []
  8.         length = len(argv)

  9.         if len(argv) >= 2 and argv[1][0] != '-':
  10.                 try:
  11.                         arg_dict['k_num'] = int(argv[1])
  12.                         length -= 1
  13.                         #debug:
  14.                         #print("; argv[1]=" + argv[1])
  15.                         #print('length=', length, end='')
  16.                         #end
  17.                         
  18.                 except Exception as err:
  19.                         # asset  Todo:  Write to log file.
  20.                         #print("\nConver argv[1] to int error:", str(Exception), str(err))
  21.                         # end
  22.                         pass
  23.         for arg in argv[len(argv)-length+1:]:  # minus first num arg if has. Plus arg[0].
  24.         # Switch option
  25.                
  26.                 if (arg == '-H' or arg == '--Hash256'):
  27.                         # arg = '-H'  # Flush --Hash256
  28.                         
  29.                         if (len(arg_dict["k_words"]) > 0) and not in_all_words("-H", "--Hash256", arg_dict):
  30.                                 print("\n-H can not occur after words. Quit.\n")
  31.                                 return -1
  32.                         if "k_H" in arg_dict:  # And arg_dict['k_H']==Ture;
  33.                                 arg_dict["k_words"].append(arg)
  34.                         else:
  35.                                 arg_dict["k_H"] = True
  36.                         length -= 1
  37.                         continue
  38.                 elif (arg == '-R'):
  39.                         if len(arg_dict["k_words"]) > 0 and not all_words("-R",arg_dict):
  40.                                 print("\n-R can not occur after words. Quit.\n")
  41.                                 return -1
  42.                         if "k_R" in arg_dict:  # And arg_dict['k_R']==Ture;
  43.                                 arg_dict["k_words"].append(arg)
  44.                         else:
  45.                                 arg_dict['k_R'] = True
  46.                         length -= 1
  47.                         continue
  48.                 elif (arg == '--help' or arg == '-h'):
  49.                         arg_dict["k_help"] = True
  50.                         def validate_help():
  51.                                 if len(argv) > 2:  # Notice here is not length.
  52.                                         print("\nMiss using the help: --help (-h) do not occur with other arguments.\n")
  53.                                         return -1
  54.                                 else:
  55.                                         return 0
  56.                         if validate_help() == 0:
  57.                                 break  # Jump out of loop.
  58.                         else:
  59.                                 return -1
  60.                 else:
  61.                         # "(-M) or (R)"
  62.                         arg_dict['k_words'].append(arg)
  63.                         length -= 1



  64.         if length > 1:  # argv[0] is programme itself. So length of left is larger than 1 (not 0).
  65.                 for word in argv[-(length-1):]:  # Reason -1 ref up.
  66.                         arg_dict['k_words'].append(word)  # validate len(arg_dict['k_words']) to make sure it has value.
  67.         if "k_help" in arg_dict:
  68.                 print("\nTo generate a more complex passwd. \
  69.                                 \ngenpasswd.py ([num] [-R] [-H|--Hash256] [words])|[-h|--help] \
  70.                                 \nnum  passwd length \
  71.                                 \nwords  words that you want to include in, seperate by blank space. \
  72.                                 \n-R shuffle the charactors. \
  73.                                 \n-H --Hash256 progress hash layer. \
  74.                                 \n-h --help   get the help notice. ")
  75.                 return 0

  76.         if len(argv) == 1 :  # Run main prog without arguments.
  77.                 # print("Using default arguments. Notice: You can input length of passwd or other arg, see --help.")
  78.                 genPasswd(20)
  79.                 return 0
  80.         #debug
  81.         print("\narg_dict:", arg_dict, "len(argv):", len(argv), "length:", length)

  82.         if 'k_words' in arg_dict:
  83.                 addWords(arg_dict['k_words'])
  84.         if 'k_help' in arg_dict:
  85.                 print("arg_dict['k_help']", arg_dict['k_help'])  # Has return , not proceed this line.
  86.         if 'k_R' in arg_dict:
  87.                 print("arg_dict['k_R']", arg_dict['k_R'])
  88.         if 'k_H' in arg_dict:
  89.                 print("arg_dict['k_H']", arg_dict['k_H'])
  90.         #end
  91.         if 'k_num' in arg_dict:
  92.                 print("argv[1]", argv[1])
  93.                 #print("arg_dict['k_num']", arg_dict['k_num'])
  94.                 genPasswd(arg_dict['k_num'])
  95.         else:
  96.                 genPasswd()
  97.         return 0
  98.         # try:
  99.         #         file = str(argv[2])
  100.         #         filePath = "/" + file
  101.                
  102.         #         #debug:
  103.         #         print(filePath)
  104.         #         print(argv)
  105.         # except Exception, err:
  106.         #         print('Make path error: ' + str(Exception) + str(err))
  107.                
  108.         # entities = []
  109.         # try:
  110.         #         entities = readEntries(filePath)
  111.         # except Exception, err:
  112.         #         print('Reading file error: ' + str(Exception) + str(err))
  113.         # result = -1
  114.         # if len(entities) > 0:
  115.         #         try:
  116.         #                 result = replaceThem(entities, notTest)
  117.         #         except Exception, err:
  118.         #                 print('Replacing error: ' + str(Exception) + str(err))
  119.         #                 traceback.print_exc()
  120.         # else:
  121.         #         print("No file to copy, check your source-data file.")
  122.         # print("------------------------------")
  123.         # if result == 0:
  124.         #         print("Done.")
  125.         #         return 0
  126.         # else:
  127.         #         print("Proceed with error, check logs.")
  128.         #         return -1

  129. if __name__ == '__main__' : main(sys.argv)
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|DiscuzX

GMT+8, 2025-4-16 13:40 , Processed in 0.013867 second(s), 18 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表