sbartell
sbartell

Reputation: 873

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).

Upvotes: 3

Views: 1959

Answers (4)

Thomas
Thomas

Reputation: 6762

If you can use python 2.7 or 3, or expect a common environment from which it might be accessible, consider argparse instead of optparse. It gives you the same control optparse does over options with arguments.

I personally don't mind putting the all the parsing in the if __name__ == '__main__' block if it's pretty straightforward.

In your comment to Falmarri's response, you mention extensive user interaction during use of your CLI program - for me, that's starting to edge towards a "line-oriented command interpreter" like the cmd in the standard libary, or the excellent cmd2. Looping over lines that are different with manually parsed raw_input's is replicating some of the functionality you could get from one of these. I'd also be interested to see good examples of what you describe.

Upvotes: 0

Spike Gronim
Spike Gronim

Reputation: 6182

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

Upvotes: 5

Mitro
Mitro

Reputation: 1626

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

Upvotes: 4

Falmarri
Falmarri

Reputation: 48577

Pretty much any python script can be a "command line program". What specific question do you have?

Upvotes: 0

Related Questions