python - 如何处理 argparse 中缺少的参数?

标签 python python-2.7 argparse default-arguments

我需要执行以下操作:

  1. if 脚本变量没有参数test == False
  2. elif 有参数 -t--test 变量 test == True
  3. else 还有另一个参数将它们作为字符串获取并传递给第三个代码

现在我收到一个错误:

# ./cli something
usage: cli [-t]
cli: error: unrecognized arguments: something

我的前两个步骤的代码:

import argparse
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-t', '--test', action="store_true")
args = parser.parse_args()
if args.test is True:
    intro = None

最佳答案

在 argparse 中,您需要将其作为单独的参数,例如:

import argparse
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-t', '--test', action="store_true")
parser.add_argument('params', nargs='+')
args = parser.parse_args()
if args.test is True:
    intro = None
elif args.params:
    pass  # process the params here
else:
    pass  # no params whatsoever

关于python - 如何处理 argparse 中缺少的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29536501/

相关文章:

python - 使用 BeautifulSoup 导航到第二个字符串文本

python - 计算 pandas 中每组的数值差异

python - 在 Python 中,如何从 argparse 深度复制 Namespace obj "args"

python - 尊重 argparse 隐私,并且。可用性

Python正则表达式匹配: ## ##

python - 运行 sys.stdout.write() 时,在我想要打印的内容之后不会打印任何内容

python - 我无法通过在 python 中继承 BaseHTTPServer 来访问成员,为什么?

python - argparse Python 2.7中一个参数的多个文件

python - scrapy 引发异常从项目目录外部运行

python - 使用 musicbrainzngs.search_releases() 返回轨道列表