Skip to content

Instantly share code, notes, and snippets.

@nafeesb
Last active March 20, 2024 22:23
Show Gist options
  • Save nafeesb/8e3d5f74cf4c4e6e5dbcc2662426bade to your computer and use it in GitHub Desktop.
Save nafeesb/8e3d5f74cf4c4e6e5dbcc2662426bade to your computer and use it in GitHub Desktop.
Useful python

Script dir

os.path.dirname(os.path.realpath(__file__))

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)

Disassemble expression

>>> 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

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

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment