Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python command line programming examples, recipes

There has been a need for python command line utilities at work lately and I have no experience in writing cli's. Regardless, I must still pop them out.

My biggest hurdle is the structure of these programs. Also, the method in getting and verifying input from the user. I have been ending up with very looong while loops and I just dont think that is the most efficient approach.

Could someone provide links to open source cli programs that I may pick to gain a bit of an understanding? Or, books, tutorials, etc that I could get my hands on. I have dug around but have had little success (my google skills must be lacking).

like image 757
sbartell Avatar asked Aug 12 '26 21:08

sbartell


2 Answers

I like baker. You use it like so:

% cat my.py
import baker


@baker.command
def cmd(start, end):
    print '%s %s' % (start, end)


if __name__ == '__main__':
    baker.run()

% python my.py cmd 2010-12-01 2010-12-31
2010-12-01 2010-12-31
like image 61
Spike Gronim Avatar answered Aug 15 '26 10:08

Spike Gronim


Random hints:

  • the optionparser module is good for parsing complex options
  • many python modules indeed are cli programs. See there (for example, see python2.6/json/tool.py which you can run with python -m json.tool)

It is a good idea to use

 def main(arguments):
     etc.

 if __name__ == '__main__':
     # only if we are executed rather than imported as a module:
     import sys
     main(sys.argv)

Such that the parts of yor app can be reused by simply importing them

like image 45
Mitro Avatar answered Aug 15 '26 11:08

Mitro



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!