- Custom timer
import time
get_time = time.perf_counter
t0 = get_time()
### some code ###
t1 = get_time()
print('Time elapsed = {}'.format(t1 - t0))- Timeit module (example taken from here)
def my_function():
try:
1 / 0
except ZeroDivisionError:
pass
if __name__ == "__main__":
import timeit
setup = "from __main__ import my_function"
print timeit.timeit("my_function()", setup=setup)import os
pathname = os.path.join('dir1', 'dir2', 'filename')
# MacOS/Linux: dir1/dir2/filename
# Windows: dir1\dir2\filenameTo run script.py you can use the following terminal command:
python script.pyHowever, if you want to run it as an executable file without calling the python command, just add the following text to the head of script.py:
#!/usr/bin/env python
# coding: utf-8Then you can run the script using
./script.pyUseful resources:
- https://packaging.python.org/tutorials/packaging-projects/
- https://kiwidamien.github.io/making-a-python-package.html
- https://medium.com/@joel.barmettler/how-to-upload-your-python-package-to-pypi-65edc5fe9c56
Load package from inside directory:
python -m pip install .Reload package (e.g., if made edits):
python -m pip install --upgrade --force-reinstall ..Note that this does not work for np.ndarrays - for those see NumPy section or pickle (below).
import json
data = {'a' : [1, 2, 3], 'b' : ('hello', 'world')} # dictionary
# save
with open('data.json', 'w') as outfile:
json.dump(data, outfile)
# load
with open('data.json', 'r') as infile:
data = json.load(infile)Can save dictionary of np.ndarrays using pickle.
import pickle
pickle.dump(dict_name, open("save.p", "wb"))
dict_name = pickle.load(open("save.p", "rb"))Use heaps:
import heapq
a = [4, 6, 2, 3, 7]
heapq.nsmallest(3, a) # [2, 3, 4]
heapq.nlargest(3, a) # [7, 6, 4]To check code against the PEP8 style guidelines can use the pycodestyle or flake8 modules (see links for installation). More notes on PEP8 here.
Check python script:
pycodestyle --first script.pyCheck Jupyter notebook:
- Install pycodestyle_magic
pip install flake8 pycodestyle_magic- Inside notebook cell (see pycodestyle_magic notes):
%load_ext pycodestyle_magic
%pycodestyle_on
%pycodestyle_off
Use black to reformat python file to match PEP8:
pip install black
black messy_file.py