Home[https://github.com/giampaolo/psutil]
psutilPython system and process utilitiesCPU
import psutil
psutil.cpu_count() # CPU
psutil.cpu_freq() # CPU
psutil.virtual_memory() #
psutil.swap_memory() #
psutil.disk_partitions() #
psutil.disk_usage('/') #
psutil.users() #
p = psutil.Process(pid) # pid
p.name() #
p.exe() #
p.cwd() #
p.cmdline() #
== 3.7 Linux & Unix ==
syslog
POSIX syslog
== 3.8 Windows ==
PyWin32
Home[http://python.net/crew/mhammond/win32/]
Windows API COM API Python Windows COM Windows
== 3.9 ==
PyInstaller
Home[http://www.pyinstaller.org/]
PyInstaller Python Python
WindowsLinuxMac OS XSolarisAIX
py2exe
Home[http://www.py2exe.org/]
Links[https://en.wikipedia.org/wiki/Py2exe Wikipedia]
py2exe PyInstaller Windows
py2app
Home[https://bitbucket.org/ronaldoussoren/py2app]
[http://www.py2exe.org/ py2exe] [http://www.py2exe.org/ py2exe] Windows [https://bitbucket.org/ronaldoussoren/py2app py2app] Mac OS X
HTTP Server
Python2 SimpleHTTPServer Python3 http.server
HTTP
import SocketServer
import SimpleHTTPServer
PORT = 8080
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print("serving at port %d" % PORT)
httpd.serve_forever()
== 4.3 Web ==
Python Web
Django
Home[https://www.djangoproject.com/]
Links[https://en.wikipedia.org/wiki/Django_(web_framework) Wikipedia] [https://zh.wikipedia.org/wiki/Django ]
Python Django Web Web ORM
Django Google Web GAE
Jython J2EE
TurboGears
Home[http://www.turbogears.org/]
Links[https://en.wikipedia.org/wiki/TurboGears Wikipedia] [https://zh.wikipedia.org/wiki/TurboGears ]
Web Django
Django Full-Stack Frameworks
CherryPy
Home[http://www.cherrypy.org/]
Links[https://en.wikipedia.org/wiki/CherryPy Wikipedia]
Web Web TurboGears
Hello world
import cherrypy
class HelloWorld(object) :
def index(self) :
return "Hello World!"
index.exposed = True
cherrypy.quickstart(HelloWorld())
web.py
Home[http://webpy.org/]
DjangoTurboGearsIt's the anti-framework framework.
[https://en.wikipedia.org/wiki/Aaron_Swartz Aaron Swartz][http://program-think.blogspot.nl/2013/01/weekly-share-37.html ]
Aaron Swartz web.py [https://en.wikipedia.org/wiki/Reddit reddit] Web 2.0
Hello world
import web
urls = (
"/", "index"
)
class index :
def GET(self) :
return "Hello, world!"
if __name__ == "__main__" :
app = web.application(urls, globals())
app.run()
Flask
Home[http://flask.pocoo.org/]
Links[https://zh.wikipedia.org/wiki/Flask ]
Web Werkzeug WSGI Jinja2
Hello world
from flask import Flask
app = Flask(__name__)
app.route("/")
def hello_world() :
return Hello World!"
if __name__ == "__main__" :
app.run()
Tornado
Home[http://www.tornadoweb.org/]
Links[https://zh.wikipedia.org/wiki/Tornado ]
Web Web.py IO
== 4.4 Web & JS ==
Pyjamas & pyjs
Home[http://pyjs.org/]
GWTGoogle Web Toolkit Python JS AJAX
Pyjamas GUI
Home[https://bitbucket.org/dundeemt/pysftp]
[https://en.wikipedia.org/wiki/SSH_File_Transfer_Protocol SFTP] ssh.py
/
import pysftp
with pysftp.Connection("hostxxx", username="userxxx", password="xxxxxx") as sftp :
with sftp.cd("public") # public
sftp.put("/my/local/filename") # public
sftp.get_r("myfiles", "/local") #
=== 5.3.4 ===
smtplib
SMTPSimple Mail Transfer Protocol
imaplib
IMAPInternet Message Access Protocol
poplib
POP3Post Office Protocol v3
yagmail
Home[https://github.com/kootenpv/yagmail]
import yagmail
yag = yagmail.SMTP("my_gmail_username", "my_gmail_password")
contents = ["This is the body, and here is just text http://somedomain/image.png",
"You can find an audio file attached.', '/local/path/song.mp3"]
yag.send("to@someone.com", "subject", contents)
=== 5.3.5 ===
Home[https://libcloud.apache.org/]
API
DNS
from libcloud.dns.types import Provider, RecordType
from libcloud.dns.providers import get_driver
cls = get_driver(Provider.ZERIGO)
driver = cls("email", "api key")
zones = driver.list_zones()
zone = [zone for zone in zones if zone.domain == "mydomain.com"][0]
record = zone.create_record(name="www", type=RecordType.A, data="127.0.0.1")
print(record)
----
= 6 =
Python API [https://www.python.org/dev/peps/pep-0249/ PEP 249]
== 6.1 ==
=== 6.1.1 ODBC ===
pyODBC
Home[https://github.com/mkleehammer/pyodbc]
pyODBC ODBC API ODBC
ODBC
import pyodbc
conn = pyodbc.connect("DSN=xxx;PWD=password")
cursor = conn.cursor()
cursor.execute("SELECT field1 FROM table1")
while True :
row = cursor.fetchone()
if not row :
break
print(row)
cursor.close()
conn.close()
ceODBC
Home[http://ceodbc.sourceforge.net/]
ODBC API
=== 6.1.2 JDBC ===
Home[https://github.com/wbolster/plyvel]
LevelDB Python Python2 Python3
import plyvel
db = plyvel.DB("/tmp/testdb/", create_if_missing=True)
db.put(b"key", b"value")
print(db.get(b"key"))
db.close()
=== 6.2.11 Berkeley DB ===
PyBSDDB
Home[http://www.jcea.es/programacion/pybsddb.htm]
Berkeley DB
== 6.3 ORMObject-Relational Mapping ==
SQLAlchemy
Home[http://www.sqlalchemy.org/]
Links[https://en.wikipedia.org/wiki/SQLAlchemy Wikipedia] [https://zh.wikipedia.org/wiki/SQLAlchemy ]
SQLAlchemy MySQLPostgreSQLSqliteOracleMS SQL ServerFirebirdSybase SQL ServerInformix
from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relation, sessionmaker
Base = declarative_base()
class Movie(Base) :
__tablename__ = "movies"
id = Column(Integer, primary_key=True)
title = Column(String(255), nullable=False)
year = Column(Integer)
directed_by = Column(Integer, ForeignKey("directors.id"))
director = relation("Director", backref="movies", lazy=False)
def __init__(self, title=None, year=None) :
self.title = title
self.year = year
def __repr__(self) :
return "Movie(%r, %r, %r)" % (self.title, self.year, self.director)
class Director(Base) :
__tablename__ = "directors"
id = Column(Integer, primary_key=True)
name = Column(String(50), nullable=False, unique=True)
def __init__(self, name=None) :
self.name = name
def __repr__(self) :
return "Director(%r)" % (self.name)
Base.metadata.create_all(create_engine("dbms://user:pwd@host/dbname"))
SQLObject
Home[http://sqlobject.org/]
Links[https://en.wikipedia.org/wiki/SQLObject Wikipedia]
SQLObject MySQLPostgreSQLSqliteMS SQL ServerFirebirdSybase SQL ServerSAP DB
from sqlobject import *
sqlhub.processConnection = connectionForURI("sqlite:/:memory:")
class Person(SQLObject) :
first_name = StringCol()
last_name = StringCol()
Person.createTable()
Peewee
Home[http://www.peewee-orm.com/]
ORM SQLiteMySQL PostgreSQL
Python2 Python3
from peewee import *
db = SqliteDatabase("test.db")
class Person(Model) :
name = CharField()
birthday = DateField()
is_relative = BooleanField()
class Meta :
database = db # This model uses the "test.db".
class Pet(Model) :
owner = ForeignKeyField(Person, related_name="pets")
name = CharField()
animal_type = CharField()
class Meta :
database = db # This model uses the "test.db".
db.connect()
db.create_tables([Person, Pet])
----
= 7 GUI =
== 7.1 GUI ==
=== 7.1.1 Tk ===
[https://en.wikipedia.org/wiki/Tk_(framework) Tk]
Tkinter & tkinter
Python Tcl/Tk
Python2 Tkinter Python3 tkinter
Tkinter Hello world
from Tkinter import *
if __name__ == "__main__" :
root = Tk()
label = Label(root, text="Hello, world")
label.pack()
root.mainloop()
=== 7.1.2 wxWidgets ===
[https://en.wikipedia.org/wiki/WxWidgets wxWidgets] C++ GUI
wxPython
Home[http://www.wxpython.org/]
Links[https://en.wikipedia.org/wiki/WxPython Wikipedia] [https://zh.wikipedia.org/wiki/WxPython ]
wxWidgets Python
[https://github.com/limodou/ulipad Ulipad] Python IDE wxPython
wxPython Hello world
import wx
class Frame(wx.Frame) :
pass
class App(wx.App) :
def OnInit(self) :
self.frame = Frame(parent=None, title="Hello, world")
self.frame.Show()
self.SetTopWindow(self.frame)
return True
if __name__ == "__main__" :
app = App()
app.MainLoop()
Home[http://lxml.de/]
C libxml libxslt Python
XPath 1.0XSLT 1.0 EXSLT HTML
=== 9.3.2 HTML ===
HTMLParser
HTML/XHTML
beautifulsoup
Home[https://www.crummy.com/software/BeautifulSoup/]
Links[https://zh.wikipedia.org/zh-cn/Beautiful_Soup ]
Beautiful Soup HTML XML
requests selenium
== 9.4 PDF ==
pyfpdf
Home[https://github.com/reingart/pyfpdf]
[http://www.fpdf.org/ FPDF] Python PDF
Hello World
from fpdf import FPDF
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", "B", 16)
pdf.cell(40, 10, "Hello, World")
pdf.output("test.pdf", "F")
HTML HTML tag
from pyfpdf import FPDF, HTMLMixin
class MyFPDF(FPDF, HTMLMixin) :
pass
pdf = MyFPDF()
pdf.add_page()
pdf.write_html(html)
pdf.output("test.pdf", "F")
Home[http://docs.wand-py.org/]
ctypes [https://en.wikipedia.org/wiki/ImageMagick ImageMagick] ImageMagick
from wand.image import Image
from wand.display import display
with Image(filename="mona-lisa.png") as img :
print(img.size)
for r in 1, 2, 3 :
with img.clone() as new_img :
new_img.resize(int(new_img.width/2), int(new_img.height/2))
new_img.rotate(90 * r)
new_img.save(filename="mona-lisa-{0}.png".format(r))
display(new_img)
Home[http://www.blender.org/]
Links[https://en.wikipedia.org/wiki/Game_Blender Wikipedia] [https://zh.wikipedia.org/wiki/Game_Blender ]
[https://en.wikipedia.org/wiki/Blender_%28software%29 Blender] C++ Python
3D AI ...
== 11.2 3D ==
Home[http://www.numpy.org/]
Links[https://en.wikipedia.org/wiki/NumPy Wikipedia] [https://zh.wikipedia.org/wiki/NumPy ]
# Python
a = range(10000000)
b = range(10000000)
c = []
for i in range(len(a)) :
c.append(a[i] + b[i])
# NumPy
import numpy as np
a = np.arange(10000000)
b = np.arange(10000000)
c = a + b