Skip to content

Instantly share code, notes, and snippets.

@nafeesb

nafeesb/python.md

Last active Feb 2, 2021
Embed
What would you like to do?
Useful python

Clear tqdm error

tqdm._instances.clear()

Extend namedtuple with methods

ExperimentProps = namedtuple( 'ExperimentProps', config.keys() )
class Experiment(ExperimentProps):
    @property
    def root_path(self):
        return self._root_path

    @root_path.setter
    def root_path(self, _val):
        if os.path.exists(_val):
            self._root_path = _val

    def network_path(self):
        return os.path.join( self._root_path, 'network', self.name)

    def get_skeleton(self):
        '''
        Load the skeleton, and return dict
        '''
        with open(self.skeleton, 'r') as f:
            skel = yaml.load(f, Loader=yaml.FullLoader)
        return skel
        
result = Experiment( *config.values() )

Simple struct

result = SimpleNamespace()
result.sizes = [ int(l[3]) for l in buf ] 
result.types = [ l[5] for l in buf ] 
result.names = [ l[6] for l in buf ] 

First item in generator

it = next(x for x in loader) item = next(iter(themap.keys()))

Interrupt tqdm

try:
    with tqdm(...) as t:
        for i in t:
            ...
except KeyboardInterrupt:
    t.close()
    raise
t.close()

Merge PDF files

import PyPDF2
tomerge = [ v for v in os.listdir('.') if 'pdf' in v ]

merger = PyPDF2.PdfFileMerger()
for f in tomerge:
    merger.append(PyPDF2.PdfFileReader( open(f, 'rb') ) )
merger.write('merged.pdf')

Flatten 2-level list

from functools import reduce
l = [['a', 'b', 'c'], ['d'], ['e', 'f']]
reduce( lambda x,y: x+y, l )

List DLLs loaded by a process

From: StackOverflow

import psutil, os
p = psutil.Process( os.getpid() )  # current proc
for dll in p.memory_maps():
  print(dll.path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment