问题
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$"
The output is:
('args:', Namespace(name='input$'))
Expected Output:
('args:', Namespace(name='input$output$'))
Can you please help figure out what am I doing wrong ? Why argparse stops parsing after encountering a special char?
回答1:
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.
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
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
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
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).
回答2:
This may be related to your shell environment, since in bash
, $
signals the start of a variable. $output
would probably be substituted for the empty string. $
on its own won't be substituted.
来源:https://stackoverflow.com/questions/37278749/python-argparse-stops-parsing-after-it-encounters