python argparse在遇到'$'后停止解析

时间:2016-05-17 14:17:34

标签: python python-3.x command-line-arguments argparse

我正在尝试使用argparse解析命令行

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$'))

你能帮忙弄清楚我做错了什么吗? 为什么argparse在遇到特殊字符后会停止解析?

2 个答案:

答案 0 :(得分:3)

这是因为大多数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$(最后一个美元符号留在那里,因为它只是一个美元符号,不能是变量的名称)。

答案 1 :(得分:0)

这可能与您的shell环境有关,因为在bash中,$表示变量的开头。 $output可能会替换空字符串。 $本身不会被替换。