-2

I'm having a strange issue with a string compare that seems to stem from my use of the argparse module to get a value from the command line. Basically the goal is to take in a number the name of a server and from there perform some action...

./this_script.py -p 3 -s serverA

The number related option works quite well, but for some reason the string related option is failing to pass my error checks.

relevant code is as follows:

parser.add_argument("-s", "--server", help="the server on which to act, either serverA or serverB")

and then the error checking (and currently debugging

if args.server:
    print "server given"
    print args.server
    if args.server is "serverA":
            print "server is " + args.server
    elif args.server is "serverB":
            print "server is " + args.server
    else:
            sys.stderr.write("error, invalid server given\n")
            sys.exit()

So when I call the script and pass it the server argument it always goes to the error condition:

~> ./this_script.py -s serverA
server given
serverA
error, invalid server serverA given

I'm fairly confident that this problem comes from the args.server, as if I hard code the server name then it works without issue.

Thanks in advance for any assistance!

MrBooks
  • 60
  • 8
  • http://stackoverflow.com/questions/2988017/string-comparison-in-python-is-vs – RyPeck Nov 15 '13 at 20:19
  • Look at `'-s serverA'.split()[-1] is 'serverA'`. If strings come from different sources they may match with `==` but not with `is`. – hpaulj Nov 15 '13 at 22:11

2 Answers2

3

Don't use is for equality comparison. It tests for object identity, and you have no guarantee that equal strings will use the same object. Use == instead.

Try

if args.server:
    print "server given"
    print args.server
    if args.server == "serverA":
            print "server is " + args.server
    elif args.server == "serverB":
            print "server is " + args.server
    else:
            sys.stderr.write("error, invalid server given\n")
            sys.exit()
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
1

This looks like a case choices.

parser.add_argument('-s','--server',choices=['serverA','serverB'])

even without a custom help line, it gives an error message like:

usage: ipython [-h] [-s {serverA,serverB}]
ipython: error: argument -s/--server: invalid choice: 'serverC' (choose from 'serverA', 'serverB')

The test that argparse uses is the equivalent to args.server in ['serverA','serverB'].

hpaulj
  • 221,503
  • 14
  • 230
  • 353