PythonSnippets

1) MATPLOTLIB CONFIGURATION

  • With Python 3.7 installed from the Windows 64-bit executable, the default matplotlibrc file is located in the following directory (see point number 4).
In [ ]:
import matplotlib
matplotlib.matplotlib_fname()
  • Remote matplotlibrc.
In [ ]:
def loadremote_mplrc(url = ''):
    import urllib3
    from matplotlib import rcParams
    http = urllib3.PoolManager()
    response = http.request('GET', url)

    P={}
    for line in response.data.splitlines():
        l=line.decode('utf-8')
        if not l.startswith("#") and not l.startswith(" ") and l:
            a=l.split(":")
            if len(a) == 2:
                try:
                    ## remove inline comments
                    b = a[1].split("#")
                    P[a[0].strip()]=b[0].strip()
                except:
                    P[a[0].strip()]=a[1].strip()

    #print(P)                
    rcParams.update(P)
In [ ]:
matplotlibrc_url = 'https://tessarinseve.pythonanywhere.com/staticweb/matplotlibrc'

loadremote_mplrc(url = matplotlibrc_url)
In [ ]:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
import math as m
In [ ]:
fig=plt.figure()
x=np.arange(10)
y=(lambda x:1+np.sqrt(x))(x)
ax=plt.gca()
ax.set_title("simple plot")
plt.plot(x,y,'bo-')

2) Matplotlib figure to Data-URI

  • Copy/paste a matplotlib figure to a markdown file encoded to a Data-URI scheme.
  • A standard use case: include a figure in a HTML presentation.
In [ ]:
def figure_to_png_datauri(fig,mime = "png"):
    from io import BytesIO
    import urllib, base64
    """Return a base64-encoded PNG from a matplotlib figure."""
    imgdata = BytesIO()#### File-like objct
    fig.savefig(imgdata, format=mime)
    imgdata.seek(0)
    data64 = base64.b64encode(imgdata.getvalue())
    return '![Figure](data:{0};base64,{1})'.format(mime, data64.decode("utf-8"))
In [ ]:
"{}".format(figure_to_png_datauri(fig))

3) Python Snippets Notebook

It's possible also to import an entire notebook as a Python module and then access the internal functions as methods. Works also on Windows with the readline module removed.

In [ ]:
import sys
import rlcompleter
## import readline not working on Windows
## readline.parse_and_bind("tab: complete")
from pathlib import Path


sys.path.append("C:\\users\\admin\\mywinpythonlib")
In [ ]:
import nbimported
sys.meta_path.append(nbimported.NotebookFinder())
In [ ]:
import  PythonSnippets
In [ ]:
PythonSnippets.loadremote_mplrc(matplotlibrc_url)

4) Startup script .bashrc (mingw64w)

The environmental variable PYTHONSTARTUP defines the user's startup s ript.

export PYTHONSTARTUP="${HOME}/.winpythonstartup.py"

In this case the.winpythonstartup.py script will be executed each time python enters the interactive mode e.g. Python REPL and Jupyter notebook with a Python kernel.

5) Pandas GUI

Save to storeddfs.py

# %load storeddfs.py
from pandasgui import show
storeddfs = [globals()[var] for var in dir() if isinstance(eval(var), pd.core.frame.DataFrame)]
show(*storeddfs)

Open Jupyter Console and type %load storeddfs.py

6) Print root directory of python.exe (REPL)

In [ ]:
import os
import sys
(os.path.sep).join((sys.executable).split(os.path.sep)[:-1])
# C:\\Users\\Seve\\AppData\\Local\\Programs\\Python\\Python39'