Python argparse在参数前添加了额外的空间 [英] Python argparse adds extra space before an argument
问题描述
我发现argparse在参数前增加了一个额外的空间.根据下面的示例代码
I found that argparse adds an extra space before an argument. Based on the example code below
def parse_arguments():
parser = argparse.ArgumentParser(
prog='sample',
description='bla bla',
parser.add_argument('-s', '--search', dest='pattern', required=True,
help='search path pattern (e.g. /dir1/dir2/*.ext)')
args = parser.parse_args()
if args.pattern[0] == ' ':
print "One space is added to the argument"
return args
并在交互式shell中测试为:
and testing in interactive shell as:
import sys
sys.argv = ['', '-s /Users/user/Desktop/test']
execfile('test.py')
将参数提供为sys.argv = ['', '-s=/Users/user/Desktop/test']
不会引起这种加法(来自 https://stackoverflow.com/a/36376287/2101864 ).
Providing the argument as sys.argv = ['', '-s=/Users/user/Desktop/test']
does not cause such an addition (inspiring from https://stackoverflow.com/a/36376287/2101864).
这是记录在案的行为还是我错过了某些事情?因为通常有一个普通用户提供参数,所以在参数标签和值之间添加了一个空格.
Is it a documented behavior or do I miss something? Because it is typical that a regular user provide argument adding a space between argument tag and value.
推荐答案
如果直接执行test.py
,将不会出现多余的空间.在交互式外壳程序中会发生这种情况,这是因为您在执行test.py
之前将sys.argv
设置为.
If you directly execute test.py
, the extra space won't occur. That happens in the interactive shell because of what you're setting sys.argv
to before executing test.py
.
sys.argv = ['', '-s /Users/user/Desktop/test']
但是从终端运行脚本并检查sys.argv
时,您得到:
But when running the script from the terminal and checking sys.argv
, you get:
['test.py', '-s', '/Users/user/Desktop/test']
从终端运行时,它还会忽略-s
和该值之间的多个空格.
It also ignores multiple spaces between -s
and the value when running from terminal.
shell/终端已经为脚本单独提供了每个参数(Python将它们放入列表中).因此,第二个参数仅是-s
而不是-s /Users/user/Desktop/test
. 在交互式外壳中执行sys.argv = ['', '-s', '/Users/user/Desktop/test']
会给出正确的结果.
The shell/terminal already provides each parameter separately to the script (and Python puts them into a list). So the 2nd param is only -s
and not -s /Users/user/Desktop/test
. Doing sys.argv = ['', '-s', '/Users/user/Desktop/test']
in the interactive shell gives the right result.
argparse 可能所做的工作是扫描sys.argv
中的每个arg,并查找所有参数名称模式-s
或--search
.一旦找到,此后的所有内容即为参数值. -s=/Users/user/Desktop/test
中的=
是标准的arg=value
表示法(在过去更是如此),因此将其解释为参数与其值之间的分隔符.
What argparse probably does is scan each arg in sys.argv
and look for all argument name patterns, -s
or --search
. Once found, everything after that is the argument value. The =
in -s=/Users/user/Desktop/test
is standard arg=value
notation (more so in the past), so it interprets that as the delimiter between an argument and its value.
这篇关于Python argparse在参数前添加了额外的空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!