Python 处理 argparse 输入中的空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18157376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Handle spaces in argparse input
提问by ofer.sheffer
Using python and argparse, the user could input a file name with -d as the flag.
使用 python 和 argparse,用户可以输入带有 -d 作为标志的文件名。
parser.add_argument("-d", "--dmp", default=None)
However, this failed when the path included spaces. E.g.
但是,当路径包含空格时,这会失败。例如
-d C:\SMTHNG\Name with spaces\MORE\file.csv
NOTE: the spaces would cause an error (flag only takes in 'C:SMTHNG\Name' as input).
注意:空格会导致错误(标志只接受 'C:SMTHNG\Name' 作为输入)。
error: unrecognized arguments: with spaces\MORE\file.csv
Took me longer than it should have to find the solution to this problem... (did not find a Q&A for it so I'm making my own post)
我花了比找到这个问题的解决方案更长的时间......(没有找到问答,所以我正在制作我自己的帖子)
采纳答案by ofer.sheffer
Simple solution: argparse considers a space filled string as a single argument if it is encapsulated by quotation marks.
简单的解决方案:argparse 将空格填充的字符串视为单个参数,如果它被引号封装。
This input worked and "solved" the problem:
此输入有效并“解决”了问题:
-d "C:\SMTHNG\Name with spaces\MORE\file.csv"
NOTICE: argument has "" around it.
注意:参数周围有“”。
回答by Illarion Kovalchuk
For those who can't parse arguments and still get "error: unrecognized arguments:" I found a workaround:
对于那些无法解析参数但仍然收到“错误:无法识别的参数:”的人,我找到了一个解决方法:
parser.add_argument('-d', '--dmp', nargs='+', ...)
opts = parser.parse_args()
and then when you want to use it just do
然后当你想使用它时就做
' '.join(opts.dmp)
回答by Uwe Brandt
Bumped into this problem today too.
今天也遇到了这个问题。
-d "foo bar"
didn't help. I had to add the equal sign
没有帮助。我必须添加等号
-d="foo bar"
and then it did work.
然后它确实起作用了。
回答by cy8g3n
After some experiments (python 2.7 Win10) I found out that the golden rule is to put quotes ("") around arguments which contain spaces and do NOTput if there are no spaces in argument. Even if you are passing a string/path. Also putting a single quotes ('') is a bad idea, at least for Windows.
经过一些实验(python 2.7 Win10),我发现黄金法则是在包含空格的参数周围加上引号(“”),如果参数中没有空格,则不要加上引号。即使您正在传递字符串/路径。加上单引号 ('') 是一个坏主意,至少对于 Windows。
Small example: python script.py --path ....\Some_Folder\ --string "Here goes a string"
小例子: python script.py --path ....\Some_Folder\ --string "这里有一个字符串"