如何将 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 me 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'])
Instead, you probably want to pass in parser.parse_args(['someTestFile'])
这篇关于如何将 python 的 argparse 与预定义的参数字符串一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!