Python noob SOS (any [former?] Perlheads out there?)

grflanagan grflanagan at yahoo.co.uk
Wed Jan 30 11:37:41 EST 2008


On Jan 29, 5:39 pm, kj <so... at 987jk.com.invalid> wrote:
[...]
> It's not the Python syntax that I'm having problems with, but rather
> with larger scale issues such as the structuring of packages,
> techniques for code reuse, test suites, the structure of
> distributions,...  Python and Perl seem to come from different
> galaxies altogether...
>
[...]
>
> I'd written a Perl module to facilitate the writing of scripts.
> It contained all my boilerplate code for parsing and validating
> command-line options, generating of accessor functions for these
> options, printing of the help message and of the full documentation,
> testing, etc.
>
> Of course, for Python now I don't have any of this, so I must write
> it all from scratch, and the thing is *I don't even know where to
> begin*!  And meanwhile works needs to get done, projects finished,
> etc.  So naturally I revert to Perl, yadda-yadda-yadda, and the
> Python project gets pushed back another week...
>
> In a way it's the usual story with learning a new language, but
> I've taught myself new languages before.  (After all, there was a
> time when I didn't know Perl.)  It's harder this time, somehow...
>

The journey of a thousand miles etc.

For command line options I get a long way with this:

[code python]
def _getargs():
    allargs = sys.argv[1:]
    args = []
    kwargs = {}
    key = None
    while allargs:
        arg = allargs.pop(0)
        if arg.startswith('--'):
            key, arg = arg.split('=', 1)
            key = key[2:]
        elif arg.startswith('-'):
            key = arg[1:]
            if not allargs or allargs[0].startswith('-'):
                allargs.insert(0, 'yes')
            continue
        if key is None:
            args.append(arg)
        else:
            kwargs[key] = arg
            key = None
    return args, kwargs

ARGS, KWARGS = _getargs()
[/code]

though obviously there's no validation.

For testing see doctest module. For file and directory manipulation
see os and shutil modules.

The following is an abuse of docstrings, but shows some OO techniques:

[code python]
import inspect

linesep = '\n'

class TemplateBase(object):
    factory = None
    template = None
    verb = 'substitute'

    @classmethod
    def render(cls, **kws):
        if cls.template is None:
            cls.template = cls.factory(inspect.getdoc(cls))
        return getattr(cls.template, cls.verb)(**kws)

    @classmethod
    def write(cls, fd, **kws):
        fd.write(linesep)
        fd.write(cls.render(**kws))
        fd.write(linesep)

    @classmethod
    def writeiter(cls, fd, seq):
        for context in seq:
            cls.write(fd, **context)

class StringTemplate(TemplateBase):
    import string
    factory = string.Template

class SafeStringTemplate(StringTemplate):
    verb = 'safe_substitute'

try:

    class TempitaTemplate(TemplateBase):
        import tempita
        factory = tempita.Template

except ImportError:
    pass

try:

    class MakoTemplate(TemplateBase):
        from mako.template import Template
        factory = Template
        verb = 'render'

except ImportError:
    pass

class StartJythonUnix(SafeStringTemplate):
    r"""
    #!/usr/bin/ksh

    java \
            -Dpython.home=$jythonhome \
            -classpath $jythonhome/jython.jar:$CLASSPATH \
            org.python.util.jython.class

    """

class DefineLocalQueue(StringTemplate):
    """
    DEFINE QLOCAL($qname) +
        DEFPSIST(YES) +
        DESCR('$descr') +
        STGCLASS('$stgclass') +
        MAXDEPTH ($maxdepth)
    """

class DeleteLocalQueue(TempitaTemplate):
    """
    DELETE QLOCAL({{qname}})
    """

import sys
StartJythonUnix.write(sys.stdout, jythonhome="/home/dev/jython/
jython-2.1")

from cStringIO import StringIO

s = StringIO()

DefineLocalQueue.write(s, name="AAA", descr="AAA", stgclass="AAA",
maxdepth=100)

DeleteLocalQueue.write(s, name="BBB", descr="BBB", stgclass="BBB",
maxdepth=100)

print s.getvalue()

[/code]

HTH

Gerard



More information about the Python-list mailing list