从命令行传递多个参数

时间:2021-05-27 10:56:22

标签: python command-line

我正在尝试

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 个传递参数,我该怎么做??

2 个答案:

答案 0 :(得分:2)

您应该使用 argparse,它比 getopt 更简单也更强大。

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

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

答案 1 :(得分:1)

在 Python 中有一个内置的 library。我强烈建议您使用它 - 您会得到很多开箱即用的东西,错误会提供更多信息。

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-d', '--dpd')
>>> args = parser.parse_args(['-d', 'bla'])
>>> args.dpd
'bla'

如果你只添加其余的参数,你的程序就会变得简单得多:

parser = argparse.ArgumentParser()
parser.add_argument('-i', '--ifile')
parser.add_argument('-o', '--ofile')
parser.add_argument('-d', '--dpd')

print(f'dpd: {args.dpd}')
print(f'input: {args.ifile}')
print(f'output: {args.ofile}')

您也可以立即获得自动退出的帮助参数。

您还可以指定哪些参数是必需的,哪些是可选的,设置默认值等等。