4

I am using Python 2.7. I am writing a script that uses argparse module for parsing command line arguments. The issue is there is an option -t, --tdiff that takes in time difference specified as +/-HH:MM:SS.

I coded the same as following, say in file myprog.py:

parser.add_argument("-t", "--tdiff",
                    action="store",
                    dest="time_diff",
                    help = "Specify time difference as +/-HH:MM:SS.")

Now I can run the program like "./myprog.py -t +02:30:00" but not as "./myprog.py -t -02:30:00".

Running the prog with time difference with leading hyphen prints the usage. Please help how can I circumvent this.

1

2 Answers 2

3

I dislike changing the option prefix to something non-standard. Here are two approaches that I've used to handle option values that begin with a hyphen.

# Use a different symbol for negative times.
--tdiff ~02:30:00

# Use this syntax on the command line.
--tdiff=-02:30:00
Sign up to request clarification or add additional context in comments.

3 Comments

+1 for the --tdiff=-XX:XX:XX option. That's what I would do too (I'm not a fan of changing the prefix-chars either).
Yup I checked. And it works without meddling with prefix_chars. Following usage works: -t=-02:30:00 or -t="-02:30:00" or -t-02:30:00. Following doesn't work: -t -02:30:00 or -t "-02:30:00".
I will accept this answer as this is closes to what I needed.
0

That - prefix is being parsed as an option, you can try to workaround this by changing the prefix used for options with prefix_chars Check out the example they give in the linked page.

1 Comment

You are totally right, quotes won't fix it. Did some search in the docs and found a correct workaround by using prefix_chars.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.