Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using OptionParser vs sys.argv

Tags:

python

For a script, I'm currently using OptionParser to add variables to an input. However, all of my current options are booleans, and it seems it would just be easier to parse using argv instead. For example:

 $ script.py option1 option4 option6 

And then do something like:

if 'option1' in argv:
    do this
if 'option2' in argv:
    do this
etc...

Would it be suggested to use argv over OptionParser when the optionals are all booleans?

like image 274
David542 Avatar asked Dec 22 '25 11:12

David542


2 Answers

"However, all of my current options are booleans, and it seems it would just be easier to parse using argv instead."

There's nothing wrong with using argv, and if it's simpler to use argv, there's no reason not to.

like image 186
Waleed Khan Avatar answered Dec 24 '25 00:12

Waleed Khan


OptionParser has been deprecated, and unless you're stuck on an older version of python, you should use the ArgParser module.

For one-off scripts, there's nothing wrong with parsing sys.argv yourself. There are some advantages to using an argument parsing module instead of writing your own.

  • Standardized. Do you allow options like "-test", because the standard is usually 2 underscores for multichar options (e.g. "--test"). With a module, you don't have to worry about defining standards because they're already defined.
  • Do you need error-catching and help messages? Because you get a lot of that for free with ArgParse.
  • Will someone else be maintaining your code? There's already lots of documentation and examples of ArgParse. Plus, it's somewhat self documenting, because you have to specify the type and number of arguments, which isn't always apparent from looking at a sys.argv parser.

Basically, if you ever expect your command line options to change over time, or expect that your code will have to be modified by someone else, the overhead of ArgParse isn't that bad and would probably save you time in the future.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!