misc:code_snippets:python
Differences
This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
| misc:code_snippets:python [2017/03/02 18:57] – Exception-safe cd hinzugefügt sascha | misc: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 | ||
| + | </ | ||
| + | |||
| + | |||
| + | ==== Mittels Pipe übergebene Daten lesen ==== | ||
| + | |||
| + | <code python> | ||
| + | import sys | ||
| + | |||
| + | # ensure the script only reads piped data and doesn' | ||
| + | if not sys.stdin.isatty(): | ||
| + | lst = [l.strip() for l in sys.stdin.readlines() if not l.startswith('#' | ||
| + | print(lst) | ||
| + | </ | ||
| + | |||
| + | |||
| + | ==== 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=/ | ||
| + | files = [] | ||
| + | path = expanduser(path) | ||
| + | |||
| + | if isdir(path): | ||
| + | files = [pjoin(abspath(path), | ||
| + | | ||
| + | elif isfile(path): | ||
| + | with open(path, ' | ||
| + | files = [l.strip() for l in lst.readlines() if not l.startswith('#' | ||
| + | |||
| + | return files | ||
| + | </ | ||
| + | |||
| + | |||
| + | ==== Anführungszeichen um einen String entfernen ==== | ||
| + | |||
| + | <code python> | ||
| + | def unquote(string): | ||
| + | """ | ||
| + | if (string[0] == string[-1]) and string.startswith(("'", | ||
| + | return string[1: | ||
| + | return string | ||
| + | </ | ||
| + | |||
| + | Ohne Überprüfen von passenden Angührungszeichen: | ||
| + | |||
| + | <code python> | ||
| + | return re.sub(r' | ||
| </ | </ | ||
| Line 251: | Line 301: | ||
| raise Exception(" | raise Exception(" | ||
| # Directory is now back to '/ | # Directory is now back to '/ | ||
| + | </ | ||
| + | |||
| + | |||
| + | ==== 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 = ['" | ||
| + | regex = [unquote(flag) for flag in flags if unquote(flag).startswith(' | ||
| + | flags = [flag for flag in flags if not any(flag for reg in regex if reg in flag)] | ||
| </ | </ | ||
misc/code_snippets/python.1488481075.txt.gz · Last modified: by sascha
