使用argparse.ArgumentParser方法的python [英] python using argparse.ArgumentParser method

查看:1266
本文介绍了使用argparse.ArgumentParser方法的python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图学习argparse.ArgumentParser的工作方式,为此我写了几行:

I've tried to learn how argparse.ArgumentParser works and I've write a couple lines for that :

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.但是,它不起作用.有没有人告诉我为什么?预先感谢

I just want to that when User run this script with 2 parameters my code assign them to firstProduct and secondProduct respectively. However it doesn’t work. Is there anyone to tell me why? thanks in advance

推荐答案

使用位置参数时,请省略dest参数.为位置参数提供的名称将是该参数的名称:

Omit the dest parameter when using a positional argument. The name supplied for the positional argument will be the name of the argument:

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')

这篇关于使用argparse.ArgumentParser方法的python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆