python - 从命令行传递多个参数
问题描述
我试着用
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 参数我该怎么做?
解决方案
您应该使用argparse
,它比getopt
.
但问题是您忘记将其声明-d
为选项:
opts, args = getopt.getopt(argv,"hi:o:d:",["ifile=","ofile=","dpd="])
推荐阅读
- xslt - 如何在 XSLT 中获取名字的首字母和姓氏
- javascript - Web蓝牙API:Origin不允许访问服务
- javascript - 嵌套对象总数
- xml - 如何在 Angular 7 中读取 XML 文件(来自不同的目录,比如来自 destop)?
- spring-boot - 如何在 c:forEach Jsp 文件中显示地图对象
- c# - 为什么我的方法以布尔值返回结果?
- html - Vue.js 类绑定,在 css 类之间插入空格
- angular - 动态更改 ngx-datatable 中的行颜色
- sql - 未知的 Sql 异常(编号 = 102,消息 = ',' 附近的语法不正确。)
- c# - 如何在自签名 https 网络服务器 C# 中添加 IP 地址而不是本地主机