7.4.33 | Linux x86_64
Server128.199.10.0
Userwww-data (uid:33)
PHP7.4.33 (apache2handler)
Terminal
Upload
Files: //lib/python3.10
View: pipes.py
"""Conversion pipeline templates. The problem: ------------ Suppose you have some data that you want to convert to another format, such as from GIF image format to PPM image format. Maybe the conversion involves several steps (e.g. piping it through compress or uuencode). Some of the conversion steps may require that their input is a disk file, others may be able to read standard input; similar for their output. The input to the entire conversion may also be read from a disk file or from an open file, and similar for its output. The module lets you construct a pipeline template by sticking one or more conversion steps together. It will take care of creating and removing temporary files if they are necessary to hold intermediate data. You can then use the template to do conversions from many different sources to many different destinations. The temporary file names used are different each time the template is used. The templates are objects so you can create templates for many different conversion steps and store them in a dictionary, for instance. Directions: ----------- To create a template: t = Template() To add a conversion step to a template: t.append(command, kind) where kind is a string of two characters: the first is '-' if the command reads its standard input or 'f' if it requires a file; the second likewise for the output. The command must be valid /bin/sh syntax. If input or output files are required, they are passed as $IN and $OUT; otherwise, it must be possible to use the command in a pipeline. To add a conversion step at the beginning: t.prepend(command, kind) To convert a file to another file using a template: sts = t.copy(infile, outfile) If infile or outfile are the empty string, standard input is read or standard output is written, respectively. The return value is the exit status of the conversion pipeline. To open a file for reading or writing through a conversion pipeline: fp = t.open(file, mode) where mode is 'r' to read the file, or 'w' to write it -- just like for the built-in function open() or for os.popen(). To create a new template object initialized to a given one: t2 = t.clone() """ # ' import re import os import tempfile # we import the quote function rather than the module for backward compat # (quote used to be an undocumented but used function in pipes) from shlex import quote __all__ = ["Template"] # Conversion step kinds FILEIN_FILEOUT = 'ff' # Must read & write real files STDIN_FILEOUT = '-f' # Must write a real file FILEIN_STDOUT = 'f-' # Must read a real file STDIN_STDOUT = '--' # Normal pipeline element SOURCE = '.-' # Must be first, writes stdout SINK = '-.' # Must be last, reads stdin stepkinds = [FILEIN_FILEOUT, STDIN_FILEOUT, FILEIN_STDOUT, STDIN_STDOUT, \ SOURCE, SINK] class Template: """Class representing a pipeline template.""" def __init__(self): """Template() returns a fresh pipeline template.""" self.debugging = 0 self.reset() def __repr__(self): """t.__repr__() implements repr(t).""" return '<Template instance, steps=%r>' % (self.steps,) def reset(self): """t.reset() restores a pipeline template to its initial state.""" self.steps = [] def clone(self): """t.clone() returns a new pipeline template with identical initial state as the current one.""" t = Template() t.steps = self.steps[:] t.debugging = self.debugging return t def debug(self, flag): """t.debug(flag) turns debugging on or off.""" self.debugging = flag def append(self, cmd, kind): """t.append(cmd, kind) adds a new step at the end.""" if not isinstance(cmd, str): raise TypeError('Template.append: cmd must be a string') if kind not in stepkinds: raise ValueError('Template.append: bad kind %r' % (kind,)) if kind == SOURCE: raise ValueError('Template.append: SOURCE can only be prepended') if self.steps and self.steps[-1][1] == SINK: raise ValueError('Template.append: already ends with SINK') if kind[0] == 'f' and not re.search(r'\$IN\b', cmd): raise ValueError('Template.append: missing $IN in cmd') if kind[1] == 'f' and not re.search(r'\$OUT\b', cmd): raise ValueError('Template.append: missing $OUT in cmd') self.steps.append((cmd, kind)) def prepend(self, cmd, kind): """t.prepend(cmd, kind) adds a new step at the front.""" if not isinstance(cmd, str): raise TypeError('Template.prepend: cmd must be a string') if kind not in stepkinds: raise ValueError('Template.prepend: bad kind %r' % (kind,)) if kind == SINK: raise ValueError('Template.prepend: SINK can only be appended') if self.steps and self.steps[0][1] == SOURCE: raise ValueError('Template.prepend: already begins with SOURCE') if kind[0] == 'f' and not re.search(r'\$IN\b', cmd): raise ValueError('Template.prepend: missing $IN in cmd') if kind[1] == 'f' and not re.search(r'\$OUT\b', cmd): raise ValueError('Template.prepend: missing $OUT in cmd') self.steps.insert(0, (cmd, kind)) def open(self, file, rw): """t.open(file, rw) returns a pipe or file object open for reading or writing; the file is the other end of the pipeline.""" if rw == 'r': return self.open_r(file) if rw == 'w': return self.open_w(file) raise ValueError('Template.open: rw must be \'r\' or \'w\', not %r' % (rw,)) def open_r(self, file): """t.open_r(file) and t.open_w(file) implement t.open(file, 'r') and t.open(file, 'w') respectively.""" if not self.steps: return open(file, 'r') if self.steps[-1][1] == SINK: raise ValueError('Template.open_r: pipeline ends width SINK') cmd = self.makepipeline(file, '') return os.popen(cmd, 'r') def open_w(self, file): if not self.steps: return open(file, 'w') if self.steps[0][1] == SOURCE: raise ValueError('Template.open_w: pipeline begins with SOURCE') cmd = self.makepipeline('', file) return os.popen(cmd, 'w') def copy(self, infile, outfile): return os.system(self.makepipeline(infile, outfile)) def makepipeline(self, infile, outfile): cmd = makepipeline(infile, self.steps, outfile) if self.debugging: print(cmd) cmd = 'set -x; ' + cmd return cmd def makepipeline(infile, steps, outfile): # Build a list with for each command: # [input filename or '', command string, kind, output filename or ''] list = [] for cmd, kind in steps: list.append(['', cmd, kind, '']) # # Make sure there is at least one step # if not list: list.append(['', 'cat', '--', '']) # # Take care of the input and output ends # [cmd, kind] = list[0][1:3] if kind[0] == 'f' and not infile: list.insert(0, ['', 'cat', '--', '']) list[0][0] = infile # [cmd, kind] = list[-1][1:3] if kind[1] == 'f' and not outfile: list.append(['', 'cat', '--', '']) list[-1][-1] = outfile # # Invent temporary files to connect stages that need files # garbage = [] for i in range(1, len(list)): lkind = list[i-1][2] rkind = list[i][2] if lkind[1] == 'f' or rkind[0] == 'f': (fd, temp) = tempfile.mkstemp() os.close(fd) garbage.append(temp) list[i-1][-1] = list[i][0] = temp # for item in list: [inf, cmd, kind, outf] = item if kind[1] == 'f': cmd = 'OUT=' + quote(outf) + '; ' + cmd if kind[0] == 'f': cmd = 'IN=' + quote(inf) + '; ' + cmd if kind[0] == '-' and inf: cmd = cmd + ' <' + quote(inf) if kind[1] == '-' and outf: cmd = cmd + ' >' + quote(outf) item[1] = cmd # cmdlist = list[0][1] for item in list[1:]: [cmd, kind] = item[1:3] if item[0] == '': if 'f' in kind: cmd = '{ ' + cmd + '; }' cmdlist = cmdlist + ' |\n' + cmd else: cmdlist = cmdlist + '\n' + cmd # if garbage: rmcmd = 'rm -f' for file in garbage: rmcmd = rmcmd + ' ' + quote(file) trapcmd = 'trap ' + quote(rmcmd + '; exit') + ' 1 2 3 13 14 15' cmdlist = trapcmd + '\n' + cmdlist + '\n' + rmcmd # return cmdlist
NameSizeActions
LICENSE.txt13.6KView Edit Del
__future__.py5KView Edit Del
__phello__.foo.py64BView Edit Del
__pycache__/--
_aix_support.py3.2KView Edit Del
_bootsubprocess.py2.6KView Edit Del
_collections_abc.py31.5KView Edit Del
_compat_pickle.py8.5KView Edit Del
_compression.py5.5KView Edit Del
_distutils_system_mod.py6.2KView Edit Del
_markupbase.py14.3KView Edit Del
_osx_support.py21.3KView Edit Del
_py_abc.py6KView Edit Del
_pydecimal.py223.3KView Edit Del
_pyio.py92.3KView Edit Del
_sitebuiltins.py3.1KView Edit Del
_strptime.py24.7KView Edit Del
_sysconfigdata__linux_x86_64-linux-gnu.py26.8KView Edit Del
_sysconfigdata__x86_64-linux-gnu.py26.8KView Edit Del
_threading_local.py7.1KView Edit Del
_weakrefset.py5.8KView Edit Del
abc.py6.4KView Edit Del
aifc.py31.8KView Edit Del
antigravity.py500BView Edit Del
argparse.py96.5KView Edit Del
ast.py58.5KView Edit Del
asynchat.py11.3KView Edit Del
asyncio/--
asyncore.py19.8KView Edit Del
base64.py20.4KView Edit Del
bdb.py31.6KView Edit Del
binhex.py14.4KView Edit Del
bisect.py3.1KView Edit Del
bz2.py11.6KView Edit Del
cProfile.py6.2KView Edit Del
calendar.py24KView Edit Del
cgi.py33.3KView Edit Del
cgitb.py11.8KView Edit Del
chunk.py5.3KView Edit Del
cmd.py14.5KView Edit Del
code.py10.4KView Edit Del
codecs.py35.9KView Edit Del
codeop.py5.5KView Edit Del
collections/--
colorsys.py3.9KView Edit Del
compileall.py19.8KView Edit Del
concurrent/--
config-3.10-x86_64-linux-gnu/--
configparser.py53.3KView Edit Del
contextlib.py25.3KView Edit Del
contextvars.py129BView Edit Del
copy.py8.5KView Edit Del
copyreg.py7.3KView Edit Del
crypt.py3.8KView Edit Del
csv.py15.7KView Edit Del
ctypes/--
curses/--
dataclasses.py55.1KView Edit Del
datetime.py86KView Edit Del
dbm/--
decimal.py320BView Edit Del
difflib.py81.4KView Edit Del
dis.py19.6KView Edit Del
distutils/--
doctest.py102.7KView Edit Del
email/--
encodings/--
enum.py38.9KView Edit Del
filecmp.py9.9KView Edit Del
fileinput.py16.1KView Edit Del
fnmatch.py6.6KView Edit Del
fractions.py27.6KView Edit Del
ftplib.py35.2KView Edit Del
functools.py37.2KView Edit Del
genericpath.py4.9KView Edit Del
getopt.py7.3KView Edit Del
getpass.py5.8KView Edit Del
gettext.py27KView Edit Del
glob.py7.7KView Edit Del
graphlib.py9.3KView Edit Del
gzip.py21.3KView Edit Del
hashlib.py10KView Edit Del
heapq.py22.3KView Edit Del
hmac.py7.5KView Edit Del
html/--
http/--
imaplib.py53.6KView Edit Del
imghdr.py3.7KView Edit Del
imp.py10.3KView Edit Del
importlib/--
inspect.py121.5KView Edit Del
io.py4.1KView Edit Del
ipaddress.py76KView Edit Del
json/--
keyword.py1KView Edit Del
lib-dynload/--
lib2to3/--
linecache.py5.6KView Edit Del
locale.py76.3KView Edit Del
logging/--
lzma.py13KView Edit Del
mailbox.py76.9KView Edit Del
mailcap.py8.9KView Edit Del
mimetypes.py22KView Edit Del
modulefinder.py23.8KView Edit Del
multiprocessing/--
netrc.py5.6KView Edit Del
nntplib.py40.1KView Edit Del
ntpath.py26.9KView Edit Del
nturl2path.py2.8KView Edit Del
numbers.py10.1KView Edit Del
opcode.py5.8KView Edit Del
operator.py10.5KView Edit Del
optparse.py59KView Edit Del
os.py38.6KView Edit Del
pathlib.py48.4KView Edit Del
pdb.py61.7KView Edit Del
pickle.py63.4KView Edit Del
pickletools.py91.3KView Edit Del
pipes.py8.7KView Edit Del
pkgutil.py24KView Edit Del
platform.py41KView Edit Del
plistlib.py27.9KView Edit Del
poplib.py14.8KView Edit Del
posixpath.py15.7KView Edit Del
pprint.py23.9KView Edit Del
profile.py22.3KView Edit Del
pstats.py28.6KView Edit Del
pty.py5.1KView Edit Del
py_compile.py7.7KView Edit Del
pyclbr.py11.1KView Edit Del
pydoc.py107.3KView Edit Del
pydoc_data/--
queue.py11.2KView Edit Del
quopri.py7.1KView Edit Del
random.py32.4KView Edit Del
re.py15.5KView Edit Del
reprlib.py5.1KView Edit Del
rlcompleter.py7.6KView Edit Del
runpy.py12.8KView Edit Del
sched.py6.2KView Edit Del
secrets.py2KView Edit Del
selectors.py19.1KView Edit Del
shelve.py8.4KView Edit Del
shlex.py13.2KView Edit Del
shutil.py53.3KView Edit Del
signal.py2.4KView Edit Del
site.py23.1KView Edit Del
sitecustomize.py155BView Edit Del
smtpd.py34.3KView Edit Del
smtplib.py44.4KView Edit Del
sndhdr.py6.9KView Edit Del
socket.py35.9KView Edit Del
socketserver.py26.7KView Edit Del
sqlite3/--
sre_compile.py27.3KView Edit Del
sre_constants.py7KView Edit Del
sre_parse.py39.8KView Edit Del
ssl.py52.5KView Edit Del
stat.py5.4KView Edit Del
statistics.py42.2KView Edit Del
string.py10.3KView Edit Del
stringprep.py12.6KView Edit Del
struct.py257BView Edit Del
subprocess.py82.9KView Edit Del
sunau.py17.7KView Edit Del
symtable.py10KView Edit Del
sysconfig.py28.7KView Edit Del
tabnanny.py11KView Edit Del
tarfile.py105.8KView Edit Del
telnetlib.py22.7KView Edit Del
tempfile.py33.8KView Edit Del
test/--
textwrap.py19.3KView Edit Del
this.py1003BView Edit Del
threading.py55.9KView Edit Del
timeit.py13.2KView Edit Del
token.py2.3KView Edit Del
tokenize.py25.3KView Edit Del
trace.py28.5KView Edit Del
traceback.py25.6KView Edit Del
tracemalloc.py17.6KView Edit Del
tty.py879BView Edit Del
turtle.py140.4KView Edit Del
types.py9.9KView Edit Del
typing.py90.4KView Edit Del
unittest/--
urllib/--
uu.py7.1KView Edit Del
uuid.py26.9KView Edit Del
venv/--
warnings.py19.2KView Edit Del
wave.py17.6KView Edit Del
weakref.py21.1KView Edit Del
webbrowser.py24.2KView Edit Del
wsgiref/--
xdrlib.py5.8KView Edit Del
xml/--
xmlrpc/--
zipapp.py7.4KView Edit Del
zipfile.py88.7KView Edit Del
zipimport.py30.2KView Edit Del
zoneinfo/--