python使用argparse.ArgumentParser方法

标签 python command-line argparse

我尝试了解 argparse.ArgumentParser 的工作原理,为此我写了几行代码:

global firstProduct
global secondProduct 
myparser=argparse.ArgumentParser(description='parser test')
myparser.add_argument("product1",help="enter product1",dest='product_1')
myparser.add_argument("product2",help="enter product2",dest='product_2')

args=myparser.parse_args()

firstProduct=args.product_1
secondProduct=args.product_2

我只想当用户使用 2 个参数运行此脚本时,我的代码将它们分别分配给 firstProductsecondProduct。然而它不起作用。有没有人告诉我为什么?提前致谢

最佳答案

使用位置参数时省略 dest 参数。为位置参数提供的名称将是参数的名称:

import argparse
myparser = argparse.ArgumentParser(description='parser test')
myparser.add_argument("product_1", help="enter product1")
myparser.add_argument("product_2", help="enter product2")

args = myparser.parse_args()
firstProduct = args.product_1
secondProduct = args.product_2
print(firstProduct, secondProduct)

运行 % test.py foo bar 打印

('foo', 'bar')

关于python使用argparse.ArgumentParser方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18335687/

相关文章:

java - 运行exec-maven-plugin java时如何获取 "[DEBUG] Executing command line:"

python-2.7 - 传递 argparse 列表时导入 python 模块

Python TK Notebook 选项卡更改检查

python - 掩码 RCNN : How to add region annotation based on manually segmented image?

Python 3.x tkinter 导入错误

python - 使用 distutils 和 deb 在 Ubuntu 系统中部署 Python 模块

linux - 我怎样才能找出这些文件或进程的作用 (linux)

java - 在不使用外部库的情况下移动 Java 命令行界面的打印位置

python - 从python中的命令行参数获取文件路径

Python argparse - 禁用子命令的帮助?