python argparse在遇到'$'后停止解析 [英] python argparse stops parsing after it encounters '$'

查看:22
本文介绍了python argparse在遇到'$'后停止解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to parse a command line using 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)

当我使用以下命令执行此操作时

When I execute this with below command

python argparser.py  --name "input$output$"

输出为:

('args:', Namespace(name='input$'))

预期输出:

('args:', Namespace(name='input$output$'))

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

Can you please help figure out what am I doing wrong ? Why argparse stops parsing after encountering a special char?

推荐答案

这是因为大多数 shell 将 $ 开头的字符串视为变量,当用双引号引用时,shell 会尝试用它的值替换它.

This is because most shells consider strings starting with $ as a variable, and when quoted with double quotes, the shell tries to replace it with its value.

>

打开一个终端/控制台并在 shell 中输入(这在 bash 和 fish 中都有效):

Jut open a terminal/console and type this in the shell (this works in both bash and fish):

echo "hi$test"  # prints hi trying to interpolate the variables 'test'
echo 'hi$test' # prints hi$test no interpolation for single quotes

这发生在 shell 启动应用程序进程之前.所以我认为在调用您的应用程序时,您需要传入由单引号引用的字符串,或者使用反斜杠转义 $.

This happens before the shell starts application processes. So I think when calling your application, you'd need to pass in the string quoted by single quotes, or escape the $ with a backslash.

echo "hi\$test" # prints hi$test since $ is escaped

如果你想查看 Python 实际从 shell 接收到什么作为参数,直接检查 sys.argv(那是 argparse 和其他类似模块读取命令的地方行参数).

If you want to see what Python actually receives from the shell as an argument, directly inspect sys.argv (that's where argparse and other modules a like read the command line arguments).

import sys
print sys.argv

在问题的这个特定情况下,会发生什么情况是您的 shell 解析了 input$output$ 并尝试插入变量 $output,但没有这样的变量定义,所以它被一个空字符串替换.所以实际上作为参数传递给 Python 的是 input$ (最后一个美元符号留在那里,因为它只是一个美元符号,不能是变量的名称).

In this specific case in the question, what happens is that your shell parses the input$output$ and tries to interpolate the variable $output, but there no such variable defined, so it gets replaced by an empty string. So what is actually being passed to Python as the argument is input$ (the last dollar sign stays in there because it's just a single dollar sign and can not be the name of a variable).

这篇关于python argparse在遇到'$'后停止解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆