如何在Python中使用argparse获取命令行参数?

发布于 2024-11-14 22:11:38 字数 424 浏览 2 评论 0原文

我希望能够在通过命令行传递选项后保存整数值。理想情况下,它是:

python thing.py -s 1 -p 0 1 2 3 -r/-w/-c
  • -s - 存储以下整数

  • -p - 存储以下整数

最后部分只能是三个选项之一(-r -w-c),具体取决于它的内容是我需要做的。

我一直在尝试阅读教程,但它们都使用相同的两个示例,但没有解释如何在 -option 之后存储整数。

I want to be able to save integer values after an option is passed through the command line. Ideally it would be:

python thing.py -s 1 -p 0 1 2 3 -r/-w/-c
  • -s - store the following integer

  • -p - store the following integers

The final part can be only one of the three options (-r, -w, or -c), depending on what it is I need to do.

I've been trying to read tutorials but they all use the same two examples that don't explain how to store integers after a -option.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

-柠檬树下少年和吉他 2024-11-21 22:11:38
>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-s', type=int)
[...]
>>> parser.add_argument('-p', type=int, nargs='*')
[...]
>>> group = parser.add_mutually_exclusive_group(required=True)
>>> group.add_argument('-r', action='store_true')
[...]    
>>> group.add_argument('-w', action='store_true')
[...]    
>>> group.add_argument('-c', action='store_true')
[...]    
>>> parser.parse_args("-s 1 -p 0 1 2 3 -r".split())
Namespace(c=False, p=[0, 1, 2, 3], r=True, s=1, w=False)
>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-s', type=int)
[...]
>>> parser.add_argument('-p', type=int, nargs='*')
[...]
>>> group = parser.add_mutually_exclusive_group(required=True)
>>> group.add_argument('-r', action='store_true')
[...]    
>>> group.add_argument('-w', action='store_true')
[...]    
>>> group.add_argument('-c', action='store_true')
[...]    
>>> parser.parse_args("-s 1 -p 0 1 2 3 -r".split())
Namespace(c=False, p=[0, 1, 2, 3], r=True, s=1, w=False)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文