Request for tips on my first python script.
Steven Bethard
steven.bethard at gmail.com
Sat Sep 9 13:25:26 EDT 2006
Lex Hider wrote:
> try:
> opts, args = getopt.getopt(sys.argv[1:], "l:",
> ["latest=", "notfound"])
> except getopt.GetoptError:
> sys.exit(2)
> #usage()
>
> for opt, arg in opts:
> if opt in ("-l", "--latest"):
> latest = int(arg)
> elif opt in ("--notfound"):
> ignoreNotFound = True #add notfound files to log
You should definitely consider using optparse or argparse_. Here's a
rewrite using argparse::
parser = argparse.ArgumentParser(description='podcast aggregator')
parser.add_argument('-l', '--latest', type=int)
parser.add_argument('--notfound', action='store_true')
values = parser.parse_args()
Then just use ``values.latest`` and ``values.notfound`` instead of
``latest`` and ``ignoreNotFound`` in the rest of your code. Using
argparse also allows you to easily add your other directories as command
line options, e.g.::
parser.add_argument('podDir', nargs='?',
default=os.path.join(HOME, 'Podcasts'))
If you then use ``values.podDir`` instead of ``podDir`` throughout your
code, your users can invoke your script in either of the following ways::
GodCast.py # no args, use "$HOME/Podcasts"
GodCast.py podcast_dir # podDir specified, use "podcast_dir"
If I were writing your script, I would add optional or positional
arguments for all of ``maxChecksPerDay``, ``myTemp``, ``downDir``,
``logFile``, ``cacheDir`` and ``feedList``.
(If you'd like your code to look more like the Python "standard", I'd
use `PEP 8`_ compliant names, e.g. ``pod_dir`` instead of ``podDir`` and
``make_dirs`` instead of ``makeDirs``.)
.. _argparse: http://argparse.python-hosting.com/
.. _PEP 8: http://www.python.org/dev/peps/pep-0008/
HTH,
STeVe
More information about the Python-list
mailing list