User Tools

Site Tools


misc:code_snippets:python

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
misc:code_snippets:python [2017/03/02 18:53] – Kurze nützliche Codeschnipsel hinzugefügt saschamisc:code_snippets:python [2017/04/11 15:13] (current) – Fix sascha
Line 72: Line 72:
 with tempfile.TemporaryDirectory() as tmp_dir: with tempfile.TemporaryDirectory() as tmp_dir:
     pass  # do stuff     pass  # do stuff
 +</code>
 +
 +
 +==== Mittels Pipe übergebene Daten lesen ====
 +
 +<code python>
 +import sys
 +
 +# ensure the script only reads piped data and doesn't wait for user input
 +if not sys.stdin.isatty():
 +    lst = [l.strip() for l in sys.stdin.readlines() if not l.startswith('#')]
 +    print(lst)
 +</code>
 +
 +
 +==== Dateien aus einem Verzeichnis erhalten oder aus Datei lesen ====
 +
 +<code python>
 +import os
 +from os.path import expanduser, isdir, isfile, abspath, join as pjoin
 +
 +def get_files(path=/some/path):
 +    files = []
 +    path = expanduser(path)
 +
 +    if isdir(path):
 +        files = [pjoin(abspath(path), f) for f in os.listdir(path) if
 +                 (isfile(pjoin(path, f)) and f.lower().endswith('.ext'))]
 +    elif isfile(path):
 +        with open(path, 'r') as lst:
 +            files = [l.strip() for l in lst.readlines() if not l.startswith('#') and l.split()]
 +
 +    return files
 +</code>
 +
 +
 +==== Anführungszeichen um einen String entfernen ====
 +
 +<code python>
 +def unquote(string):
 +    """Remove matching pair of single or double quotes around string"""
 +    if (string[0] == string[-1]) and string.startswith(("'", '"')):
 +        return string[1:-1]
 +    return string
 +</code>
 +
 +Ohne Überprüfen von passenden Angührungszeichen:
 +
 +<code python>
 +return re.sub(r'^["\']|["\']$', '', string)
 </code> </code>
  
Line 224: Line 274:
 progress_simple(total) progress_simple(total)
 progress(total, 40, '#', '-') progress(total, 40, '#', '-')
 +</code>
 +
 +
 +==== Verzeichnis temporär wechseln (Exception-safe) ====
 +
 +<code python cd_exception_safe.py>
 +from contextlib import contextmanager
 +import os
 +
 +@contextmanager
 +def cd(newdir):
 +    prevdir = os.getcwd()
 +    os.chdir(os.path.expanduser(newdir))
 +    try:
 +        yield
 +    finally:
 +        os.chdir(prevdir)
 +
 +# cd using context manager and decorator
 +# directory is reverted even after an exception is thrown
 +
 +os.chdir('/home')
 +
 +with cd('/tmp'):
 +    # ...
 +    raise Exception("There's no place like home.")
 +# Directory is now back to '/home'.
 +</code>
 +
 +
 +==== Liste mit Inhalt einer anderen Liste filtern ====
 +
 +<code python>
 +# filter a list by checking if substring of another list is contained in entries of the list to be filtered
 +# here flags is some list which contain entries from the list regex --> filter matching regex from list flags
 +flags = ['"s/regex/looking/g"', 'options', '"s/another/regex/"', '--more flags']
 +regex = [unquote(flag) for flag in flags if unquote(flag).startswith('s/')]
 +flags = [flag for flag in flags if not any(flag for reg in regex if reg in flag)]
 </code> </code>
  
misc/code_snippets/python.1488480834.txt.gz · Last modified: by sascha