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!
3 Answers 3
I think optparse can do this.
2 Comments
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).
Comments
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.
3 Comments
Explore related questions
See similar questions with these tags.
./somescript.py arg --optional_arg="value"is clearer, and more standard. Why do you prefer your approach?./somescript.py add <alias> -- "netstat -nlp | grep pie"Which would optionally assign an alias to that entry - to me its clearer due to the nature of the program (take everything at the end as is).