Фишки Python
29 subscribers
2 photos
3 files
29 links
Всё что ты хотел узнать, но ленился спросить.

Декораторы, итераторы и контракты.
Download Telegram
import dominate
from dominate.tags import *

doc = dominate.document(title='Main Page')

with doc.head:
meta(charset="utf-8")

with doc.body:
h1("hello!")

print(str(doc))
Инфа по процессору, памяти, диску и сети psutil

import psutil
import os, sys, time

pid = os.getpid()
p = psutil.Process(pid)

print('Process info:')
print(' name :', p.name())
print(' exe :', p.exe())

data = []
while True:
data += list(range(100000))
info = p.memory_full_info()
# Convert to MB
memory = info.uss / 1024 / 1024
print('Memory used: {:.2f} MB'.format(memory))
if memory > 40:
print('Memory too big! Exiting.')
sys.exit()
time.sleep(1)
Process info:
name : Python
exe : /usr/local/Cellar/.../Python
Memory used: 11.82 MB
Memory used: 14.91 MB
Memory used: 18.77 MB
Memory used: 22.63 MB
Memory used: 26.48 MB
Memory used: 30.34 MB
Memory used: 34.19 MB
Memory used: 38.05 MB
Memory used: 41.90 MB
Memory too big! Exiting.
Кроссплатформенный мониторинг изменений файловой системы watchdog

from watchdog.observers import Observer
from watchdog.events import (PatternMatchingEventHandler, FileModifiedEvent, FileCreatedEvent)

observer = Observer()
class Handler(PatternMatchingEventHandler):
def on_created(self, event: FileCreatedEvent):
print('File Created: ', event.src_path)
def on_modified(self, event: FileModifiedEvent):
print('File Modified: %s [%s]' % (
event.src_path, event.event_type))

observer.schedule(event_handler=Handler('*'), path='.')
observer.daemon = False
observer.start()

try:
observer.join()
except KeyboardInterrupt:
print('Stopped.')
observer.stop()
observer.join()
File Created: ./secrets.txt
File Modified: . [modified]
File Modified: ./secrets.txt [modified]
File Modified: ./secrets.txt [modified]
File Modified: ./secrets.txt [modified]
File Modified: ./secrets.txt [modified]
Stopped.
API maker - hug

hug is a library that provides an extremely simple way to create
Internet APIs for web services.
import hug
import webcolors

@hug.get()
def hextoname(hex: hug.types.text):
return webcolors.hex_to_name('#' + hex)

@hug.get()
def nametohex(name: hug.types.text):
return webcolors.name_to_hex(name)
hug -f hugserve.py
$ curl http://localhost:8000/hextoname?hex=ff0000
"red"

$ curl http://localhost:8000/nametohex?name=lightskyblue
"#87cefa"
Date times
arrow - работа со временем без оглядки на timezones
import arrow

t0 = arrow.now()
print(t0)

t1 = arrow.utcnow()
print(t1)

difference = (t0 - t1).total_seconds()
print('Total difference: %.2f seconds' % difference)
2016-06-26T18:43:55.328561+10:00
2016-06-26T08:43:55.328630+00:00
Total difference: -0.00 seconds
Время в человеческом виде

>>> t0 = arrow.now()
>>> t0.humanize()
'just now'

>>> t0.humanize()
'seconds ago'

>>> t0 = t0.replace(hours=-3,minutes=10)
>>> t0.humanize()
'2 hours ago'
>>> t0.humanize(locale='ru')
'2 часа назад'
Парсинг даты из кучи вариантов - parsedatetime
import parsedatetime as pdt

cal = pdt.Calendar()

examples = [
"2016-07-16",
"2016/07/16",
"2016-7-16",
"2016/7/16",
"07-16-2016",
"7-16-2016",
"7-16-16",
"7/16/16",
"19 November 1975",
"19 November 75",
"19 Nov 75",
"tomorrow",
"yesterday",
"10 minutes from now",
"the first of January, 2001",
"3 days ago",
"in four days' time",
"two weeks from now",
"three months ago",
"2 weeks and 3 days in the future",
]

print('{:30s}{:>30s}'.format('Input', 'Result'))
print('=' * 60)

for e in examples:
dt, result = cal.parseDT(e)
print('{:<30s}{:>30}'.format('"' + e + '"', dt.ctime()))
Input Result
============================================
"2016-07-16" Sat Jul 16 16:25:20 2016
"2016/07/16" Sat Jul 16 16:25:20 2016
"2016-7-16" Sat Jul 16 16:25:20 2016
"2016/7/16" Sat Jul 16 16:25:20 2016
"07-16-2016" Sat Jul 16 16:25:20 2016
"7-16-2016" Sat Jul 16 16:25:20 2016
"7-16-16" Sat Jul 16 16:25:20 2016
"7/16/16" Sat Jul 16 16:25:20 2016