首页 > 解决方案 > 从命令行传递多个参数

问题描述

我试着用

import sys, getopt

def main(argv):
   inputfile = ''
   outputfile = ''
   dpd = ''
   opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile=","dpd="])

   print(opts)
   
   for opt, arg in opts:
      print(opt)
      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
      elif opt in ("-d","--dpd"):
         dpd = arg
   print ('Input file is ', inputfile)
   print ('Output file is ', outputfile)
   print ('DPD', dpd)

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

并运行,python3 demo.py -i 65 -o ale -d 45但它给出了错误

getopt.GetoptError:无法识别选项 -d

我想通过 6 pass 参数我该怎么做?

标签: pythoncommand-line

解决方案


您应该使用argparse,它比getopt.

但问题是您忘记将其声明-d为选项:

opts, args = getopt.getopt(argv,"hi:o:d:",["ifile=","ofile=","dpd="])

推荐阅读