手动将命令传递给 argparse? | Python 2.7
Manually pass commands into argparse? | Python 2.7
我正在使用 Python 出色的 Cmd 库制作终端游戏。但我很好奇我是否能以某种方式将 argparse 代码放入其中。就像使用 argparse 来处理来自我的 cmd.Cmd() class 的 'args'。
为此,我真的希望 argparse 有办法手动将 args 传递给它。我浏览了文档,但没有注意到类似的东西。
parse_args()
takes an optional argument args
with a list (or tuple) of to parse. parse_args()
(without arguments) is equivalent to parse_args(sys.argv[1:])
:
In a script, parse_args()
will typically be called with no arguments, and the ArgumentParser
will automatically determine the command-line arguments from sys.argv
.
如果您没有元组,只有一个字符串,shell-like 参数拆分可以使用 shlex.split()
完成
>>> shlex.split('"A" B C\ D')
['A', 'B', 'C D']
请注意 argparse
将打印用法和帮助消息以及 exit()
致命错误。你可以覆盖 .error()
来自己处理错误:
class ArgumentParserNoExit(argparse.ArgumentParser):
def error(self, message):
raise ValueError(message) # or whatever you like
我正在使用 Python 出色的 Cmd 库制作终端游戏。但我很好奇我是否能以某种方式将 argparse 代码放入其中。就像使用 argparse 来处理来自我的 cmd.Cmd() class 的 'args'。 为此,我真的希望 argparse 有办法手动将 args 传递给它。我浏览了文档,但没有注意到类似的东西。
parse_args()
takes an optional argument args
with a list (or tuple) of to parse. parse_args()
(without arguments) is equivalent to parse_args(sys.argv[1:])
:
In a script,
parse_args()
will typically be called with no arguments, and theArgumentParser
will automatically determine the command-line arguments fromsys.argv
.
如果您没有元组,只有一个字符串,shell-like 参数拆分可以使用 shlex.split()
>>> shlex.split('"A" B C\ D')
['A', 'B', 'C D']
请注意 argparse
将打印用法和帮助消息以及 exit()
致命错误。你可以覆盖 .error()
来自己处理错误:
class ArgumentParserNoExit(argparse.ArgumentParser):
def error(self, message):
raise ValueError(message) # or whatever you like