class ClassName(object):
def __init__(self, foo):
self.foo = foo
@classmethod
def bar(cls, arg):
...
def foo(self, bar):
return super(MyClass, self).foo(bar)
@classmethod
def subclass_map(cls):
map = {c.__name__: c for c in cls.__subclasses__()}
for subclass in map.values():
map.update(subclass.subclass_map())
return map
request = urllib2.Request(url)
request.get_method = lambda : 'HEAD'
response = urllib2.urlopen(request)
print response.info()['Last-Modified']
url = 'http://www.sno.phy.queensu.ca/~phil/exiftool/'
request = urllib2.Request(url)
response = urllib2.urlopen(request)
data = response.read()
http://www.pip-installer.org/en/latest/installing.html
curl https://raw.github.com/pypa/pip/master/contrib/get-pip.py | sudo python
sudo -H python -m ensurepip
http://fonnesbeck.github.com/ScipySuperpack/
time.sleep(seconds)
dt = datetime.datetime.now()
t1 = datetime.datetime.now()
xxx
t2 = datetime.datetime.now()
print '{:0.1f}s'.format((t2 - t1).total_seconds())
modification_time = datetime.datetime(*email.utils.parsedate(urllib2_response.info()['Last-Modified'])[:6])
datetime.datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%fZ")
timestamp = time.mktime(some_datetime.timetuple())
os.utime(file_path, (timestamp, timestamp))
datetime.datetime.fromtimestamp(os.stat(path).st_mtime)
t1 = datetime.datetime.now()
...
age_seconds = (datetime.datetime.now() - t1).seconds
datetime.datetime.now().strftime('%Y%m%d-%H%M%S')
import datetime
date = datetime.datetime.utcfromtimestamp(0)
def unix_time_millis(dt):
return (dt - epoch).total_seconds() * 1000.0
import datetime
utcdatetime = datetime.datetime.utcfromtimestamp(unix_timestamp)
localdatetime = datetime.datetime.fromtimestamp(unix_timestamp)
http://stackoverflow.com/a/3168394/182781
raise Exception('foo')
try:
...
except Exception as e:
print ''.join(traceback.format_exception(*sys.exc_info())[1:-2])
print ANSIColor.wrap(str(e), color=ANSIColor.red)
status = subprocess.call(['git', 'status', '--porcelain', self.path])
status = subprocess.check_call(['git', 'status', '--porcelain', self.path])
output = subprocess.check_output(['git', 'status', '--porcelain', self.path])
def validate_sudo():
pwd = ''
for i in range(5):
sp = subprocess.Popen(['sudo', '-S', '-v'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
sp.communicate(pwd + '\n')
if sp.returncode == 0:
return True
pwd = getpass.getpass()
return False
@classmethod
def ensure_superuser(cls):
if os.getuid() != 0:
print 'Relaunching with sudo...'
os.execv('/usr/bin/sudo', ['/usr/bin/sudo'] + sys.argv)
@contextlib.contextmanager
def chdir_to_path(self, path):
oldwd = os.getcwd()
os.chdir(path)
try:
yield
except:
os.chdir(oldwd)
raise
os.chdir(oldwd)
def foo(self):
with self.chdir_to_path(self.path):
foo
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug('foo')
logging.warning('foo')
logging.error('foo')
Based on args:
if self.args.verbose:
logging.basicConfig(level=logging.DEBUG)
with open('x.txt') as x: f = x.read()
with open('x.txt') as x: f = x.readlines()
for dirpath, dirnames, filenames in os.walk(path, topdown=True):
...
contents = os.listdir(path)
pep8 file.py
autopep8 -d --ignore E501 file.py
autopep8 -i --ignore E501 file.py
match = re.search(r'pattern', string)
print match.group(1)
for match in re.finditer(r'pattern', string)
print match.group(1)
re.sub(r'pattern', replace, string)
str.splitlines()
def underscore_to_camel_case(underscore_value):
return re.sub(r'(\w)_(\w)', lambda match: match.group(1) + match.group(2).upper(), underscore_value)
def camel_case_to_underscore(camelcase_value):
return re.sub(r'([a-z])([A-Z])', lambda match: match.group(1) + '_' + match.group(2).lower(), camelcase_value)
'foo [{:<5}] bar'.format(value)
'foo [{1:<{0}}] bar'.format(field_width, value)
del list[:]
http://docs.python.org/2/tutorial/datastructures.html#the-del-statement
for k, v in globals().items():
...
for index, item in enumerate(iterable):
...
versions = [tuple(map(int, (i.split('.')))) for i in version_strings]
sorted(versions, cmp)
Support in pkg_resources (http://stackoverflow.com/questions/11887762/compare-version-strings):
import pkg_resources
pkg_resources.parse_version('1.2.3') < pkg_resources.parse_version('4.5.6')
dict.get(key, default)
getattr(object, key, default)
for i in range(0, len(items), 50):
x = items[i:i + 50]
'cafebabe'.decode('hex')
binascii.unhexlify('cafebabe')
binascii.a2b_hex('cafebabe')
binascii.b2a_hex(binary)
binascii.hexlify(binary)
python <<EOF
from IPython.external.mathjax import install_mathjax
install_mathjax()
EOF
os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
data = plistlib.readPlistFromString(stdoutdata)
import xml.etree.ElementTree
tree = xml.etree.ElementTree.parse(path)
tree = xml.etree.ElementTree.fromstring(xml_string)
http://quickies.seriot.ch/index.php?id=180
import objc
objc.loadBundle("InstantMessage", globals(),
bundle_path=objc.pathForFramework(u'/System/Library/Frameworks/InstantMessage.framework'))
service = IMService.serviceWithName_('AIM')
print service.peopleWithScreenName_('pikswiss')
from AddressBook import *
book = ABAddressBook.sharedAddressBook()
print book.me()
The macholib
module can replace otool for some purposes, for example getting a binary's UUID:
Replace
otool -l /Applications/Foo.app/Contents/MacOS/Foo | grep uuid
with
python -c 'import macholib.MachO, uuid, sys; binary = macholib.MachO.MachO(sys.argv[1]); uuid_command, = [c[1] for c in binary.headers[0].commands if type(c[1]) == macholib.mach_o.uuid_command]; print uuid.UUID(bytes=uuid_command.uuid)' /Applications/Foo.app/Contents/MacOS/Foo
or
python - /Applications/Foo.app/Contents/MacOS/Foo <<-EOF
import macholib.MachO, uuid, sys
binary = macholib.MachO.MachO(sys.argv[1])
uuid_command, = [c[1] for c in binary.headers[0].commands if type(c[1]) == macholib.mach_o.uuid_command]
print uuid.UUID(bytes=uuid_command.uuid)
EOF
call (char *)PyUnicode_AsUTF8((void *)PyObject_Repr($arg2))