Python sys.argv and argparser conflict

huangapple go评论91阅读模式
英文:

Python sys.argv and argparser conflict

问题

以下是您提供的代码部分的翻译:

  1. import argparse
  2. import sys
  3. # 定义一个 argparse 解析器
  4. parser = argparse.ArgumentParser()
  5. parser.add_argument('--foo', help='foo 帮助')
  6. # 使用 argparse 解析参数
  7. args = parser.parse_args()
  8. # 访问来自 argparse 的 --foo 值
  9. if args.foo:
  10. print(f'--foo 设置为 {args.foo}')
  11. # 访问 sys.argv 的值
  12. if len(sys.argv) > 1:
  13. print(f'第一个位置参数是 {sys.argv[1]}')

我的运行结果:

  1. # 这个是成功的!
  2. python foo.py "asdasd"
  3. 用法foo.py [-h] [--foo FOO]
  4. foo.py: 错误: 无法识别的参数: asdasd
  5. # 这个是失败的!
  6. python foo.py --foo "asdasd"
  7. --foo 设置为 asdasd
  8. 第一个位置参数是 --foo
英文:

I'm trying to mixed-use both argument handlers but failed. Python doesn't allow me to do so or do there exist some ways to handle mixed usage?

  1. import argparse
  2. import sys
  3. # Define an argparse parser
  4. parser = argparse.ArgumentParser()
  5. parser.add_argument('--foo', help='foo help')
  6. # Parse the arguments using argparse
  7. args = parser.parse_args()
  8. # Access the value of --foo from argparse
  9. if args.foo:
  10. print(f'--foo is set to {args.foo}')
  11. # Access the value of sys.argv
  12. if len(sys.argv) > 1:
  13. print(f'The first positional argument is {sys.argv[1]}')

my running result:

  1. # this one ok!
  2. python foo.py "asdasd"
  3. usage: foo.py [-h] [--foo FOO]
  4. foo.py: error: unrecognized arguments: asdasd
  5. # this one fail!
  6. python foo.py --foo "asdasd"
  7. --foo is set to asdasd
  8. The first positional argument is --foo

答案1

得分: 1

你可以同时使用它们。argparse 是一个以用户友好的方式处理命令行参数的模块。sys.argv 是一个包含你的命令行参数的列表。

  1. # 使用 argparse 解析参数
  2. args, remaining_args = parser.parse_known_args()
  3. # 访问 sys.argv 的值
  4. if len(sys.argv) > 1 and sys.argv[1] not in remaining_args:
  5. print(f'第一个位置参数是 {sys.argv[1]}')
英文:

You can use both of them. argparse is a module to handle CLA in a user friendly way. sys.argv is a list that contains your CLA.

  1. # Parse the arguments using argparse
  2. args, remaining_args = parser.parse_known_args()
  3. # Access the value of sys.argv
  4. if len(sys.argv) > 1 and sys.argv[1] not in remaining_args:
  5. print(f'The first positional argument is {sys.argv[1]}')

huangapple
  • 本文由 发表于 2023年3月9日 18:33:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75683386.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定