r/Python • • Jun 18 '13

Creating python command-line applications

http://pauloortins.com/creating-python-command-line-applications/
0 Upvotes

20 comments sorted by

10

u/westurner Jun 18 '13

7

u/ScriptSimian Jun 18 '13

I was going to post argparse. Building a CLI as suggested is error prone and not to be undertaken except for didactic purposes.

1

u/pauloortins Jun 18 '13

Agree, the best way is using optparse or argparse =D

3

u/abledanger Jun 18 '13

Just found optparse yesterday, even though it's a standard library. It's awesome.

10

u/nemec Jun 18 '13

optparse is deprecated, I'd stick to argparse (which is brilliant, IMO). (for proof, check out the 2.7 docs)

2

u/talideon Jun 18 '13

Or better yet: docopt.

5

u/EmmEff Jun 18 '13

As a long time Python developer, I would recommend that anybody learning the language to NOT pay any attention to this article. It is careless to omit any sort of error checking, command-line options, etc., in a command-line tool. At least look at the built-in module argparse.

3

u/guibou Jun 18 '13

I don't really think this short script is wrong. What can really happen? If you don't pass something which is an int in sys.argv[2:4], you'll get a ValueError. If you don't pass something which is not a correct operation in sys.argv[1], you'll get a KeyError. I agree it is not "explicit error handling", but for a simple program like that I'm not really sure you really want to add so much logic for error checking, I mean, it is a simple program, so keep it simple.

The question of the pertinence of this article and of a linking in reddit is more important. Should we link on reddit a blog post everytime we discover a trivial feature of a language ? (Look mum, I know how to print a value...). This code is so trivial that it may be compacted in one line (changing a bit the behavior, I agree):

import operator, sys
print(getattr(operator, sys.argv[1])(*map(int, sys.argv[2:4])))

(I agree it is a bit over compacted, let's do something readable)

import operator
import sys

operation = getattr(operator, sys.argv[1])
operand = map(int, sys.argv[2:])

print(operation(*operand))

(Interested readers may notice a minor difference in behavior between my two version, the why is let as an exercise for the reader).

Version with rough error checking:

import operator
import sys

try:
    operation = getattr(operator, sys.argv[1])
except (AttributeError, IndexError):
    sys.exit("You must provide a correct operation as first argument. Availables ones are {}.".format(', '.join(dir(operator))))
try:
    operand = list(map(int, sys.argv[2:]))
except ValueError:
    sys.exit("You must provid integer arguments after your operation.")

try:
    print(operation(*operand))
except TypeError:
    sys.exit("Your operation takes more or less integer arguments.")

I think error checking here is too overkill for such a simple program ;)

(Edit: code formating) (Edit: typo)

1

u/pauloortins Jun 18 '13 edited Jun 18 '13

I thought the same about error checking, otherwise, I pretend to build a more complex script so was good to know better libraries to do that.

About the relevance, for me it values a post, I have seen people searching stuffs like that in several languages. About reddit, I don't know, I started to participate now and I have seen links like this one, maybe they are the exceptions. Don't forget that it's managed by the community , up and down votes should be used for this reason.

Anyway, ASAP, I will rewriting it using argparse.

1

u/guibou Jun 18 '13

Google gives really good results when you look for "command line parsing python" or "command line arguments python"...

For the community stuff, I agree that the community will vote, but unfortunately some communities contains so much noise that users stop to use them. By the way, there is other posts on your blog which should be posted on reddit, but that one was really too much trivial.

1

u/pauloortins Jun 18 '13 edited Jun 18 '13

You are right my friend. I agree with you.

8

u/utdemir Jun 18 '13

Also,

import operator

functions = {
	'add': operator.add
	'subtract': operator.sub
	'multiply': operator.mul
	'divide': operator.truediv
}

instead of

functions = {
'add': lambda num1, num2: num1 + num2,
'subtract': lambda num1, num2: num1 - num2,
'multiply': lambda num1, num2: num1 * num2,
'divide': lambda num1, num2: num1 / num2
}    

8

u/eliben Jun 18 '13

Direct sys.argv manipulation, no command-line options, no error checking... This is not how one creates real command-line tools in Python.

7

u/XNormal Jun 18 '13

docopt, anyone?

3

u/talideon Jun 18 '13

Yes! Always docopt. It's the best thing that ever happened to command line parsing in Python.

2

u/nomadismydj Jun 18 '13

sys.argv is a good place to start but im sure youll out grow it when you want to do complex behavior via flags. check out: http://docs.python.org/dev/library/argparse.html or even http://docs.python.org/2/library/optparse.html

2

u/[deleted] Jun 18 '13 edited Jun 19 '13

This seems like a bit of Python code you had written long ago when you were learning and decided to pull out for a blog post.

Part of creating good Python applications is using the standard library effectively (argparse, operator) and using community assets (docopt, clint, etc) to spend your time solving specific problems, not ones that have already been solved.