Monday, February 7, 2011

Ignore optparse if value is given

I would like to have the ability to pass an argument w/o having to specify an option for optparse. If I do pass an option, it has to be a known option or else the script will fail.

Rsync the following file to destination

myscript.py filename

Rsync the following folder to destination (all this is figured out in function I create).

myscript.py -f foldername

The reason is, I have an array (or dict) that ties with the "foldername." If no options are passed, the argument given in the CLI is a file that's in the working folder where the user calls the script. Passing -f means to upload a folder whose value is stored in a dict (user can be in any directory, this folder's path is known ahead of time).

Am I better off adding options for both options? -f for file and -v for folder aka version?

  • I am always a fan of being explicit, but you can short circuit optparse.

    # args[0] is always the executable's name
    if len(args) > 1:
        parser.parse_args(args, options)
    else:
        #open file
    
    Garrett Hyde : If args = sys.argv, remember that len(args) is always >= 1. This is because argv[0] is the name of the script.
    luckytaxi : `> 2` doesn't work. `> 1` works
    NorthIsUp : ha, thanks, I had that at first but changed it for some reason.
    From NorthIsUp
  • Treat -f as an option with no argument and use it to switch the behavior of the positional argument (i.e. foldername).

    From kanaka
  • parser.parse_args() always returns two values:

    • options, an object containing values for all of your options
    • args, the list of positional arguments leftover after parsing options

    (Totorial)

    As such, you could do something like this:

    parser = OptionParser()
    parser.add_option("-f", "", action="store_true", dest="folder", default=False)
    (options, args) = parser.parse_args(sys.argv)
    
    fname = args[1] # name of folder or file
    
    if options.folder:
        # do stuff for folder
    else:
        # do stuff for file
    

0 comments:

Post a Comment