Last active
November 6, 2017 10:58
-
-
Save royvandam/8604dea0257ed7e04e6f29abb63b1a99 to your computer and use it in GitHub Desktop.
Small collection of Python utility functions and classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import tempfile, os, shutil | |
import socket, errno | |
import subprocess | |
import platform | |
class dotdict(dict): | |
__getattr__ = dict.get | |
__setattr__ = dict.__setitem__ | |
__delattr__ = dict.__delitem__ | |
def ping(hostname): | |
command = ['ping'] | |
if platform.system().lower() == 'windows': | |
command.extend(['-n', '1', '-w', '1000']) | |
else: | |
command.extend(['-c', '1']) | |
command.append(hostname) | |
with open(os.devnull, 'w') as shutup: | |
exit_code = subprocess.call(command, | |
stdout=shutup, stderr=shutup) | |
return exit_code == 0 | |
def pingPort(hostname, port): | |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
s.settimeout(1) | |
result = s.connect_ex((hostname, port)) | |
if result == 0: | |
s.close() | |
return True | |
return False | |
def formatList(data): | |
return '$[' + ' '.join(['%02x' % x for x in data]) + ']' | |
class Service: | |
def __init__(self, name): | |
self.name = name | |
def _exec_service(self, action): | |
with open(os.devnull, 'w') as shutup: | |
exit_code = subprocess.call( | |
['service', self.name, action], | |
stdout=shutup, stderr=shutup) | |
return exit_code == 0 | |
def isRunning(self): | |
return self._exec_service('status') | |
def start(self): | |
return self._exec_service('start') | |
def stop(self): | |
return self._exec_service('stop') | |
def restart(self): | |
return self._exec_service('restart') | |
class AutoRestore: | |
def __init__(self, path, callback=None): | |
self.path = path | |
self.callback = callback | |
self.temp = tempfile.mkstemp() | |
def __enter__(self): | |
with open(self.path, 'rb') as fsrc: | |
with os.fdopen(self.temp[0], 'wb') as fdst: | |
shutil.copyfileobj(fsrc, fdst) | |
def __exit__(self, exception_type, exception_value, traceback): | |
shutil.move(self.temp[1], self.path) | |
if callable(self.callback): | |
self.callback() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment