0

I'm following the example at https://docs.python.org/2/library/getopt.html for parsing command line options. I'm almost a newbie with python. Like the example my code is:

import getopt, sys
import pdb

config_filename = 'config.py'
orders_filename = 'default.out'
db_filename = 'sqlite.db'
action = False

def main():
  c_args_parse()
  print action

def c_args_parse():

  pdb.set_trace()
  try:
    (opts, args) = getopt.getopt(sys.argv[1:], "hc:d:o:s:")
  except getopt.GetoptError as err:
    # print help information and exit:
    print '\n' + str(err) # will print something like "option -a not recognized"
    usage()
    sys.exit(2)

  for o, a in opts:
    if o in ("-h", "--help"):
      usage()
      exit()
    elif o in ("-c", "--config"):
      config_filename = a
    elif o in ("-d", "--db"):
      db_filename = a
    elif o in ("-o", "--output"):
      orders_filename = a
    elif o in ("-s", "--sync"):
      action = a
    else:
      assert False, "\nUnhandled option"
  if not action:
    print '\nSpecifying a sync action is required'
    usage()
    sys.exit(2)

def usage():
    usage = """
    BESync [hcdo] -s orders|products|availablity

    -h --help              Prints this help
    -c --config (arg)      Path to config file
    -d --db (arg)          Path to sqlite db
    -o --output (arg)      Path to orders output file (arg)
    -s --sync (arg)        Actions (arg): orders, products, availability
    """
    print usage


if __name__ == "__main__":
  main()

Within the for loop, variable a seems to be empty while tuple (o,a) is fine.

running pdb trace:

$ python test.py -s orders
test.py(16)c_args_parse()
-> try:
(Pdb) n
> ./test.py(17)c_args_parse()
-> (opts, args) = getopt.getopt(sys.argv[1:], "hc:d:o:s:")
(Pdb) 
> ./test.py(24)c_args_parse()
-> for o, a in opts:
(Pdb) 
> ./test.py(25)c_args_parse()
-> if o in ("-h", "--help"):
(Pdb) o,a
('-s', 'orders')
(Pdb) o
'-s'
(Pdb) a
  # returns nothing

Any explanation for this?

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
coddoc
  • 65
  • 1
  • 8
  • `a` cannot be empty. More likely, it contains `None`. – kindall Aug 11 '14 at 15:25
  • This isn't relevant to your problem, but I suggest not doing `assert False, "\nUnhandled option"`. The user can [disable asserts](http://stackoverflow.com/questions/1273211/disable-assertions-in-python) from the command line using the `-O` flag. Perhaps you could raise a `ValueError` or something, instead. – Kevin Aug 11 '14 at 15:29
  • FYI, "*Users who would like to write less code and get better help messages should consider using the [`argparse`](https://docs.python.org/2/library/argparse.html#module-argparse) module instead.*" -- https://docs.python.org/2/library/getopt.html – Robᵩ Aug 11 '14 at 15:34

2 Answers2

1

Shooting from the hip here - but really don't make it hard on yourself. Use http://docopt.org/ for option parsing. I can't see anything obviously wrong in your code, but that's probably just me. I'll run it when I have some time ;-)

(edit) It looks like action is being shadowed. One of the reasons I usually prefer a more functional style (let c_args_parse return stuff, not set global variables) is that I'm too lazy to delve into the rules of the various languages I use about shadowing. Add "global action" to the top of the function and it will now work (and ditto for the other variables you set). Still - think about returning stuff, working with global variables is not considered very good style.

cdegroot
  • 1,765
  • 11
  • 12
1

a doesn't do what you think it does. a is a debugger command which prints the arguments to the current function.

Try p a to print the value of the expression a.

Robᵩ
  • 163,533
  • 20
  • 239
  • 308