Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/github/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用argparse解析命令行参数_Python_Argparse - Fatal编程技术网

Python 使用argparse解析命令行参数

Python 使用argparse解析命令行参数,python,argparse,Python,Argparse,我有一个传递多个参数和require元素的实用程序,任何人都可以提供一些输入,我如何使用argparse处理这个场景。请查找示例代码 #! /usr/bin/env python import argparse parser = argparse.ArgumentParser() parser.add_argument("-cdl", dest = "input_file") args = parser.parse_args() print args Command Line : pytho

我有一个传递多个参数和require元素的实用程序,任何人都可以提供一些输入,我如何使用argparse处理这个场景。请查找示例代码

#! /usr/bin/env python
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-cdl", dest = "input_file")
args = parser.parse_args()
print args

Command Line :  python test_6.py -cdl sample (workfine)

utility also pass :  python test_6.py -cdl sample -cdl-sp -cdl-ck

工具的最后两个参数。作为我的程序,我需要获取示例文件并忽略其余两个参数,没有任何错误。在当前代码中,它给我错误

您可以为不需要的参数添加选项

parser.add_argument("-cdl-sp", dest = "sp",  action='store_true')
parser.add_argument("-cdl-sk", dest = "sk",  action='store_true')
休息应该是平等的

['-cdl-sp', '-cdl-ck']

如果您想避免这种情况(不建议这样做),应该说“invalide choice:-cdl sp”,看看这一点,您可能能够在错误发生时进行测试,并且在无提示的情况下失败,但它不包含任何值。python test_6.py-cdl sample-cdl sp-cdl ckWith“action='store'u true'”解析器不需要任何值。若参数存在,你们将得到一个布尔值true,若参数不存在,则为false。这也是一个有效的语句,但上面的解决方案更适合我。当我为调用工具编写包装器时,一些用户可以添加更多选项,我无需更改任何代码,但感谢回复
['-cdl-sp', '-cdl-ck']