## Script dir `os.path.dirname(os.path.realpath(__file__))` ## Clear tqdm error `tqdm._instances.clear()` ## Extend namedtuple with methods ```python 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 ```python 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 ```python try: with tqdm(...) as t: for i in t: ... except KeyboardInterrupt: t.close() raise t.close() ``` ## Merge PDF files ```python 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 ```python 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](https://stackoverflow.com/questions/5553917/how-to-list-all-dlls-loaded-by-a-process-with-python) ```python import psutil, os p = psutil.Process( os.getpid() ) # current proc for dll in p.memory_maps(): print(dll.path) ``` ## Disassemble expression ```python >>> import dis >>> dis.dis("not x is None") 1 0 LOAD_NAME 0 (x) 2 LOAD_CONST 0 (None) 4 COMPARE_OP 9 (is not) 6 RETURN_VALUE >>> dis.dis("x is not None") 1 0 LOAD_NAME 0 (x) 2 LOAD_CONST 0 (None) 4 COMPARE_OP 9 (is not) 6 RETURN_VALUE ``` ## Dynamic enums ```python actstr = 'stand,walk,run,sit' Actions = Enum('Actions', { v:i for i,v in enumerate(actstr.split(',')) }) Actions.run Actions['run'] Actions.run.name # string name Actions.run.value # index ``` ## Get IP address ```python def get_IP_address(): import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('www.apple.com', 80)) # Connect to LDAP. This does not actually need to route. ipaddr = s.getsockname()[0] s.close() return ipaddr ```