Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using python argparse module for arguments starting with hyphen

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.

like image 850
Subhajit Kundu Avatar asked Sep 05 '25 03:09

Subhajit Kundu


1 Answers

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
like image 70
FMc Avatar answered Sep 07 '25 20:09

FMc