我正在尝试使用am解析来解析命令行。
from argparse import ArgumentParser
argparser = ArgumentParser(prog="parse", description="desc")
create.add_argument("--name",dest="name",required=True,help="Name for element")
args = argparser.parse_args()
print(args)
当我用下面的命令执行这个命令时
python argparser.py --name "input$output$"
产出如下:
('args:', Namespace(name='input$'))
预期产出:
('args:', Namespace(name='input$output$'))
你能帮我找出我做错了什么吗?为什么a解析在遇到特殊字符后停止解析?
发布于 2016-05-17 07:02:12
这是因为大多数shell都将以$开头的字符串视为变量,当使用双引号引用时,shell试图用它的值替换它。
Jut打开一个终端/控制台并在shell中键入它(这在bash和fish中都适用):
echo "hi$test" # prints hi trying to interpolate the variables 'test'
echo 'hi$test' # prints hi$test no interpolation for single quotes
这发生在shell启动应用程序进程之前。因此,我认为在调用应用程序时,需要传入单引号引用的字符串,或者用反斜杠转义$。
echo "hi\$test" # prints hi$test since $ is escaped
如果您想将Python作为参数从shell中实际接收到什么,直接检查sys.argv
(这是argparse
和其他模块读取命令行参数的地方)。
import sys
print sys.argv
在这个问题中的特定情况下,您的shell解析input$output$
并尝试插值变量$output
,但是没有定义这样的变量,因此它被一个空字符串替换。因此,实际上传递给Python的是input$
(最后一个美元符号留在那里,因为它只是一个美元符号,不能是变量的名称)。
发布于 2016-05-17 06:21:11
这可能与您的shell环境有关,因为在bash
中,$
表示变量的开始。$output
可能会被空字符串替换。$
本身是不会被取代的。
https://stackoverflow.com/questions/37278749
复制