使用 argparse 解析字符串
Parsing a string using argparse
所以我希望argparse的输入是字符串而不是命令行。
例如:
python3 some_script.py arg1 arg2 arg3
我想给 argparse 字符串 "arg1 arg2 arg3"
import argparse
command = "arg1 arg2 arg3"
parser = argparse.ArgumentParser()
# add args here
args = parser.parse_args()
# process the command here and extract values
您可以直接在 parse_args()
中使用列表 - 通常第一个元素是脚本的名称,但您可以使用任何字符串
args = parser.parse_args( ["script.py", "arg1", "arg2", "arg3"] )
或者您可以使用您的线路
command = "arg1 arg2 arg3"
args = parser.parse_args( ["script.py"] + command.split(" ") )
你总是可以把它放在 sys.argv
中,parser
应该使用它
import sys
sys.argv = ["script", "arg1", "arg2", "arg3"]
如果您想 append()
从命令行
获得的值的某些选项,它会很有用
sys.argv.append( "--debug" )
如果你有更复杂的 command
和 " "
like
'arg1 "Hello World" arg3'
然后你可以使用标准模块 shlex 将其正确拆分为三个参数
import shlex
shlex.split('arg1 "Hello world" arg3')
['arg1', 'Hello World', 'arg3'].
正常command.split(" ")
会给出错误的四个参数
['arg1', '"Hello', 'World"', 'arg3']
所以我希望argparse的输入是字符串而不是命令行。 例如:
python3 some_script.py arg1 arg2 arg3
我想给 argparse 字符串 "arg1 arg2 arg3"
import argparse
command = "arg1 arg2 arg3"
parser = argparse.ArgumentParser()
# add args here
args = parser.parse_args()
# process the command here and extract values
您可以直接在 parse_args()
中使用列表 - 通常第一个元素是脚本的名称,但您可以使用任何字符串
args = parser.parse_args( ["script.py", "arg1", "arg2", "arg3"] )
或者您可以使用您的线路
command = "arg1 arg2 arg3"
args = parser.parse_args( ["script.py"] + command.split(" ") )
你总是可以把它放在 sys.argv
中,parser
应该使用它
import sys
sys.argv = ["script", "arg1", "arg2", "arg3"]
如果您想 append()
从命令行
sys.argv.append( "--debug" )
如果你有更复杂的 command
和 " "
like
'arg1 "Hello World" arg3'
然后你可以使用标准模块 shlex 将其正确拆分为三个参数
import shlex
shlex.split('arg1 "Hello world" arg3')
['arg1', 'Hello World', 'arg3'].
正常command.split(" ")
会给出错误的四个参数
['arg1', '"Hello', 'World"', 'arg3']