sys.argv is munging my command line options

Discussion in 'Python' started by Chris Allen, Aug 29, 2007.

  1. Chris Allen

    Chris Allen Guest

    The command line syntax for my program is as follows:

    action key=value key=value...

    Where action is a required string (ie. 'backup', 'init', 'restore',
    etc) and the program can accept one or more key value pairs. I know
    this syntax isn't standard, but I think it works great for my program
    as each key can override an identically named field in a configuration
    file, that way the user doesn't have to have two different syntaxes to
    do the same thing. I could do this with --key value, but key=value is
    cleaner IMHO because it matches the config file syntax.

    But I'm running into a problem with this which is that sys.argv splits
    my key=value options. I need to know the option associations, and
    there's no way to know this by inspecting sys.argv. Can I get access
    to the command line string as python saw it before it split it into
    sys.argv or is there another way? Thanks.
     
    Chris Allen, Aug 29, 2007
    #1
    1. Advertisements

  2. Chris Allen

    Ant Guest

    Could you show us some example code that demonstrates this? The
    following works as expected for me on win32:

    # test.py
    import sys

    for arg in sys.argv[1:]:
    print arg
    C:\0>test.py action key=value key=value
    action
    key=value
    key=value
     
    Ant, Aug 29, 2007
    #2
    1. Advertisements

  3. Chris Allen

    Chris Allen Guest

    Thanks for the reply. Oops... I forget that I was calling the program
    from a shell script, the shell script was responsible for goofing up
    my command line options. Solved. Thanks again.


     
    Chris Allen, Aug 29, 2007
    #3
  4. Chris Allen escribió:
    It's ok for a personal script, but if you expect other people to use it,
    you should consider the "Rule of Least Surprise" and follow the standard.

    Anyway, using getopt or optparse, it would be "--key=value", or perhaps
    "-o key=value / --option=key=value"
    I can't see the problem, sys.argv[1:] gives you the list of ordered
    key/value pairs... give an example of what you want and what you get.
     
    Arnau Sanchez, Aug 29, 2007
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.