且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 argparse 解析带有前导减号(负数)的位置参数

更新时间:2023-02-10 20:12:48

您需要在命令行参数中插入 -- :

You need to insert a -- into your command-line arguments:

$ python example.py --test -- -1,2,3,4
Namespace(positional='-1,2,3,4', test=True)

双破折号停止 argparse 寻找更多可选开关;这是处理命令行工具这个用例的事实上的标准方法.

The double-dash stops argparse looking for any more optional switches; it's the defacto standard way of handling exactly this use case for command-line tools.