I have problem using OptionParser in python. When I give '&' as one of the character in input it will discard the '&' and characters next to it are treated as separate command. Here is the sample code for test.py:
from optparse import OptionParser
cmdParser = OptionParser()
cmdParse.add_option("-n", "--USER", help="User Name")
cmdParse.add_option("-p", "--PASSWORD", help="Password")
(options, args) = cmdparser.parse_args()
uname = options.USER
pwd = options.PASSWORD
When I run it with command: python test.py -n sample -p 123&45 password it reads only 123 and sayd 45 is not recognized as interna and external command error. All other special symbols works fine except '&'. It works fine if I give -p "123&45". But I don't want to specify string explicitly. Is it a limitation with OptionParser? Any help is appreciable.
Thanks in advance.
This is not a problem with
optparse
- your program never sees anything beyond the ampersand because that is interpreted by your shell. "&" is used in many shells to start a command in the background. So your command line is being interpreted as "runpython test.py -n sample -p 123
in the background and then run the command45
", explaining your error. The solution is to quote your option, as you have already found out. This is a limitation of the shell and can not be fixed by anything you do in Python as the program never sees the whole option.PS: You shouldn't be using
optparse
anymore - rather useargparse
.