• pipes —- Interface to shell pipelines
    • Template Objects

    pipes —- Interface to shell pipelines

    源代码:Lib/pipes.py


    The pipes module defines a class to abstract the concept of a pipeline—- a sequence of converters from one file to another.

    Because the module uses /bin/sh command lines, a POSIX or compatibleshell for os.system() and os.popen() is required.

    The pipes module defines the following class:

    • class pipes.Template
    • An abstraction of a pipeline.

    示例:

    1. >>> import pipes
    2. >>> t = pipes.Template()
    3. >>> t.append('tr a-z A-Z', '--')
    4. >>> f = t.open('pipefile', 'w')
    5. >>> f.write('hello world')
    6. >>> f.close()
    7. >>> open('pipefile').read()
    8. 'HELLO WORLD'

    Template Objects

    Template objects following methods:

    • Template.reset()
    • Restore a pipeline template to its initial state.

    • Template.clone()

    • Return a new, equivalent, pipeline template.

    • Template.debug(flag)

    • If flag is true, turn debugging on. Otherwise, turn debugging off. Whendebugging is on, commands to be executed are printed, and the shell is givenset -x command to be more verbose.

    • Template.append(cmd, kind)

    • Append a new action at the end. The cmd variable must be a valid bourne shellcommand. The kind variable consists of two letters.

    The first letter can be either of '-' (which means the command reads itsstandard input), 'f' (which means the commands reads a given file on thecommand line) or '.' (which means the commands reads no input, and hencemust be first.)

    Similarly, the second letter can be either of '-' (which means the commandwrites to standard output), 'f' (which means the command writes a file onthe command line) or '.' (which means the command does not write anything,and hence must be last.)

    • Template.prepend(cmd, kind)
    • Add a new action at the beginning. See append() for explanations of thearguments.

    • Template.open(file, mode)

    • Return a file-like object, open to file, but read from or written to by thepipeline. Note that only one of 'r', 'w' may be given.

    • Template.copy(infile, outfile)

    • Copy infile to outfile through the pipe.