在Python中从命令行解析带空格的字符串 [英] Parsing a string with spaces from command line in Python
问题描述
有没有一种方法可以在python中调用程序并将其传递给我希望其解析的字符串,而无需将该字符串声明为'我要解析的字符串'
,而是将其声明为 String解析
Is there a way to call my program in python and pass it a string I want it to parse without declaring the string as 'String I want to parse'
but as String I want to parse
import argparse
#Parse command line for input
parser = argparse.ArgumentParser(description='Parse input string')
#position input argument
parser.add_argument('string', help='Input String')
args = parser.parse_args()
arg_str = args.string
print(arg_str)
当我运行 $ python test.py我想解析的字符串
时,出现错误: test.py:错误:无法识别的参数:我想解析
when I run $ python test.py String I want to parse
I get the error: test.py: error: unrecognized arguments: I want to parse
是否仍然要告诉脚本考虑空格并将输入作为一个字符串,直到到达输入的末尾或到达另一个解析参数(例如 -s
)为止?
Is there anyway to tell the script to account for spaces and take the input as one string until either the end of the input is reached or another parse argument such as -s
is reached?
推荐答案
如果您真的想使用argparse,请添加 nargs ='+'
或 nargs ='*'
到 add_argument
:
If you really want to use argparse add nargs='+'
or nargs='*'
to add_argument
:
import argparse
parser = argparse.ArgumentParser(description='Parse input string')
parser.add_argument('string', help='Input String', nargs='+')
args = parser.parse_args()
arg_str = ' '.join(args.string)
print(arg_str)
python test.py abc xyz
将产生 abc xyz
. *
表示可以空列表,而 +
至少需要一个单词.
python test.py abc xyz
will produce abc xyz
. *
means that empty list is ok and +
requires at least one word.
或者,如果您不需要任何花哨的内容,则可以只使用sys.arg:
Alternatively you may just user sys.arg if you don't need anything fancy:
import sys
arg_str = ' '.join(sys.argv[1:]) # skip name of file
print(arg_str)
如果可以的话,我真的很喜欢 docopt ,所以我推荐它:
And if I may, I really like docopt so I would recommend it:
"""Usage:
test.py <input>...
"""
import docopt
arguments = docopt.docopt(__doc__)
input_argument = ' '.join(arguments['<input>'])
print(input_argument)
Docopt根据帮助消息生成解析器,非常好.
Docopt generates parser based on help message, it's so great.
这篇关于在Python中从命令行解析带空格的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!