Skip to content Skip to sidebar Skip to footer

Python Argparse Stops Parsing After It Encounters '$'

I am trying to parse a command line using argparse from argparse import ArgumentParser argparser = ArgumentParser(prog='parse', description='desc') create.add_argument('--name',d

Solution 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).


Solution 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.


Post a Comment for "Python Argparse Stops Parsing After It Encounters '$'"