views:

48

answers:

3

If possible I would like to use the following structure for a command however I can't seem to figure out how to achieve this in Python:

./somescript.py arg <optional argument> -- "some long argument"

Would it be possible to achieve this in a feasible manner without too much dirty code? Or should I just reconsider the syntax (which is primarily preference).

Thanks!

A: 

You just need to stick something like this on the first line: #/usr/local/bin/python

Just make yours be wherever your python binary is located.

As for args look at getopt or optparser

And remember to chmod your file to make it executable.

Khorkrak
I think you may have misunderstood the question - it's about parsing the arguments in a specific way within the Python program.
WinkyWolly
hmm yeah I guess I don't quite get the question. How come you can't just use getopt to do this? [getopt in python](http://docs.python.org/library/getopt.html) What's different about your syntax?
Khorkrak
@Khorkrak, the user doesn't want to use dashes before his "arg" and "optional arg".
Alex Martelli
+2  A: 

I think optparse can do this.

Forest
It does. Everything after "--" is an argument. Everything before is an option.
S.Lott
Mildly embarassed I missed that..Thanks!
WinkyWolly
+1  A: 

If you don't want to use dashes in front of your arg and optional_argument, that's kind of strange by typical Unix command-line behavior, but I don't understand why every answer appears to believe you have to use the dashes. Avoiding them is kind of trivial, actually...:

import sys

def before_and_after_doubledashes(args=sys.argv):
    where_doubledashes = args.index('--') if '--' in args else len(args)
    return args[:where_doubledashes], args[where_doubledashes+1:]

This completely ignores whether args start with dashes or not, just singles out the first occurrence of an arg that's exactly a double dash (if any) and returns a tuple of two lists, one all the args that are before that double dash if any, one all the args that are after it (empty if there's no double dash argument). You can assign these lists from the call:

before, after = before_and_after_doubledashes()

then treat them as you will (check their lengths, assign variables from part of them, etc).

Alex Martelli