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

Next revision
Previous revision
misc:code_snippets:python [2016/09/29 12:08] – created saschamisc:code_snippets:python [2017/04/11 15:13] (current) – Fix sascha
Line 21: Line 21:
             raise e             raise e
         sys.exit(1)         sys.exit(1)
 +</code>
 +
 +
 +==== Liste zeilenweise ausgeben ====
 +
 +<code python>
 +print(*myList, sep='\n')
 +</code>
 +
 +
 +==== Erstes Listenelement oder None erhalten ====
 +
 +<code python>
 +next(iter(your_list or []), None)
 </code> </code>
  
Line 48: Line 62:
 else: else:
     print('The for loop is over.')     print('The for loop is over.')
 +</code>
 +
 +
 +==== Temporäres Verzeichnis als Context Manager verwenden ====
 +
 +<code python>
 +import tempfile
 +
 +with tempfile.TemporaryDirectory() as tmp_dir:
 +    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 200: 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>
  
Line 401: Line 513:
 # vim: set ai ts=4 sw=4 sts=4 noet fileencoding=utf-8 ft=python # vim: set ai ts=4 sw=4 sts=4 noet fileencoding=utf-8 ft=python
  
 +'''
 +This module provides functions to color string in the terminal output
 +and provides a logging class with colored strings
 +'''
 +
 +__version__ = '1.0'
  
 # Colored output # Colored output
Line 427: Line 545:
  
 def color_string(string, color): def color_string(string, color):
-    format = ''+    fmt = ''
     if color in COLORS:     if color in COLORS:
-        format = COLOR_SEQ % (30 + COLORS[color]) + string + RESET_SEQ+        fmt = COLOR_SEQ % (30 + COLORS[color]) + string + RESET_SEQ
     elif color in range(8):     elif color in range(8):
-        format = COLOR_SEQ % (30 + color) + string + RESET_SEQ+        fmt = COLOR_SEQ % (30 + color) + string + RESET_SEQ
     else:     else:
-        format = string +        fmt = string 
-    return format+    return fmt 
 + 
 +def bold_string(string): 
 +    return BOLD_SEQ + string + RESET_SEQ
  
 def print_color(string, color): def print_color(string, color):
     print(color_string(string, color))     print(color_string(string, color))
 +
 +import sys
 +
 +def print_error(string):
 +    print(color_string(string, RED), file=sys.stderr)
  
 import logging import logging
Line 492: Line 618:
 print_color("just a cyan colored info", 'CYAN') print_color("just a cyan colored info", 'CYAN')
 print_color("and a magenta/purple one, too", MAGENTA) print_color("and a magenta/purple one, too", MAGENTA)
 +
 +print_error('[ERROR] This will be written to stderr')
  
 #str = "this is a test string" #str = "this is a test string"
misc/code_snippets/python.1475150931.txt.gz · Last modified: by sascha