如何在预定义的参数字符串中使用python的argparse? [英] How can I use python's argparse with a predefined argument string?
问题描述
我想使用pythons argparse模块来解析我的cli参数字符串.这对于从终端传递的参数有效,但不适用于给定的字符串.
I want to use the pythons argparse module to parse my cli parameter string. This works for the parameters a pass from terminal, but not with a given string.
import argparse
parser = argparse.ArgumentParser(description='Argparse Test script')
parser.add_argument("param", help='some parameter')
argString = 'someTestFile'
print(argString)
args = parser.parse_args(argString)
如果运行此脚本,则会得到以下输出:
If I run this script I get this output:
~/someTestFile
usage: argparsetest.py [-h] param
argparsetest.py: error: unrecognized arguments: o m e T e s t F i l e
~/someTestFile
在o m e T e s t F i l e
中以某种方式进行了转换.如前所述,如果我从终端传递文件名,它就可以工作.
The ~/someTestFile
is somehow transformed in o m e T e s t F i l e
. As already mentioned, it works if I pass the filename from the terminal.
我可以想象,这与字符串编码有关.有人知道如何解决此问题吗?
I could imagine, that this has something to do with string encodings. Does someone has an idea how to fix this?
推荐答案
parser.parse_args()
要求序列与sys.argv[1:]
相同.如果将字符串像sys.argv序列一样对待,则会得到['s', 'o', 'm', 'e', 'T', 'e', 's', 't', 'F', 'i', 'l', 'e']
. s成为相关参数,然后字符串的其余部分不可解析.
parser.parse_args()
expects a sequence in the same form as sys.argv[1:]
. If you treat a string like a sys.argv sequence, you get ['s', 'o', 'm', 'e', 'T', 'e', 's', 't', 'F', 'i', 'l', 'e']
. 's' becomes the relevant argument, and then the rest of the string is unparseable.
相反,您可能想传递parser.parse_args(['someTestFile'])
这篇关于如何在预定义的参数字符串中使用python的argparse?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!