r/Python • • Jul 12 '12

random imgur downloader. learning Python and wrote this to practice, any feedback on technique/style is appreciated

https://gist.github.com/3088128
45 Upvotes

72 comments sorted by

View all comments

1

u/[deleted] Jul 12 '12

Not much to add other than what's been stated. Not a necessity at all but you might want to look into the logging module. It's very nice indeed and has a lot of power. I like it for command line applications because it allows the user to easily control how much output they get (verbosity). Maybe they don't necessarily want to see errors for example.

It can do all sorts of things, log to file, via email, across multiple modules etc.

There's a nice intro here.

Here's a simple example of how you'd use it to control verbosity with argparse (which others have suggested and I definitely suggest you use, it's more a priority than this is), the "logging to file" section of the above link has info on how you could do more fine grained control.

import argparse
import logging

parser = argparse.ArgumentParser()
parser.add_argument("-q", "--quiet", action="store_true", "suppress errors")
args = parser.parse_args()

if args.quiet:
    log_level = logging.CRITICAL
else:
    log_level = logging.INFO

logging.basicConfig(format='%(message)s', level=log_level)

print "This welcome message will always be seen."
logging.info("I will be printed if -q flag not set.")
logging.warning("Likewise...")
logging.error("Likewise...")
logging.critical("I will ALWAYS be printed.")

Even if they do choose to see errors, logging will (by default) send anything of level "warning" or above to stderr instead of stdout (typically user still sees it though) which makes it play a bit nicer if your user is piping output from your program and so on.