golb

Python

How to print the error name

import traceback

try:
    #code here
except Exception as exception:
    print(type(exception).__name__)
    print(exception.__class__.__name__)
    print(exception.__class__.__qualname__)
    print(traceback.format_exc())

Reference : stackOverflow

Super easy multiprocess

from multiprocessing import Pool

def multi_process(my_func, my_args, num_processes=10):
    """my_args is a table of arguments for my_func"""
    results = []

    with Pool(processes=num_processes) as pool:
        for result in pool.imap(my_func, my_args):
            results.append(result)

    return results

How to get the path of the current folder

import pathlib
pathlib.Path(__file__).parent.resolve()

How to get the KeyboardInterrupt

try:
    #code here
except KeyboardInterrupt:
    pass
    #or do something

Pylint

python3 -m pip install pylint
pylint <filename>

The Zen of Python

python -c "import this"

Get the path to a package

python -c "import numpy as _;print(_.__path__)"
python -c "import numpy as _;print(_.__file__)"

Simple http server

python -m http.server

Pip config

Location:

# show the location
pip config debug
# location location and config
pip config -v list

Poor man's JSON parser/loader

Can be useful for loading log data that is not properly formatted JSON. Note that this can be unsecure (RTFM).

import ast

weird_json = """{'a': 1, 'b': "2"}"""

obj = ast.literal_eval(weird_json)
print(type(obj["a"]), "=", obj["a"])  # <class 'int'> = 1
print(type(obj["b"]), "=", obj["b"])  # <class 'str'> = 2