Show Menu
Cheatography

Intermediate Python Cheat Sheet by

A cheat sheet for various modules in the Python programming language.

Built-in Functions

float()
int()
bin(num)
hex(num)
dict()
list()
tuple()
str()
complex(a, b)
bool(x)
set()
sorted(s)
bytes(s)
bytear­­ray(s)
abs(num)
len(s)
max(s)
min(s)
ord(char)
chr(num)
pow(x,y)
range(­­[s­tart] : stop : [step])
round(num, places)
sum(s)
open(f­­il­e­name, [mode])
type(obj)
id(obj)
divmod­­(num, divisor)
input(­­pr­ompt)
print(s)

JSON Module

dump(obj, fp, skipke­ys=­False, ensure­_as­cii­=True, check_­cir­cul­ar=­True, allow_­nan­=True, cls=None, indent­=None, separa­tor­s=None, defaul­t=None, sort_k­eys­=False, **kw)
Serialize obj as a JSON formatted stream to fp (a .write­()-­sup­porting file-like object)
dumps(­[same arguments as above, minus "­fp"])
Serialize obj to a JSON formatted str
load([same as dump])
Deseri­alize fp (a .read(­)-s­upp­orting file-like object containing a JSON document) to a Python object
loads(s, [same arguments as dumps])
Deseri­alize s (a str instance containing a JSON document) to a Python object
JSON functions have a lot of arguments, you'll only need to use "­obj­", "­fp", and "­s" about 99% of the time though

Subprocess Module

subpro­ces­s.r­un(­args, *, stdin=­None, input=­None, stdout­=None, stderr­=None, shell=­False, timeou­t=None, check=­False)
The recomm­ended approach to invoking subpro­cesses. This does not capture stdout or stderr by default. To do so, pass subpro­ces­s.PIPE to the approp­riate arguments
subpro­ces­s.c­all­(args, *, stdin=­None, stdout­=None, stderr­=None, shell=­False, timeou­t=None)
Run the command described by args. Wait for command to complete, then return the returncode attribute
subpro­ces­s.c­hec­k_o­utp­ut(**)
Run command with arguments and return its output. Same as run(..., check=­True, stdout­=PI­PE).stdout
Note that "­**" means to use the same arguments as above

Time Module

time.c­lock()
On Unix, return the current processor time as a floating point number expressed in seconds
time.s­lee­p(secs)
Suspend execution of the calling thread for the given number of seconds

Datetime Module

dateti­me.d­ate()
An idealized date
dateti­me.t­ime()
An idealized time
dateti­me.d­at­eti­me(­year, month, day, hour=0, minute=0, second=0, micros­eco­nd=0, tzinfo­=None)
A combin­ation of time and date
dateti­me.t­im­ede­lta­(da­ys=0, seconds=0, micros­eco­nds=0, millis­eco­nds=0, minutes=0, hours=0, weeks=0)
A time difference
dateti­me.t­oday()
Return the current day
dateti­me.n­ow­(tz­=None)
Return the current time and date
dateti­me.d­ate()
Return the date portion of a datetime object
dateti­me.t­ime()
Return the time portion of a datetime object
dateti­me.w­ee­kday()
Return the day of the week. Monday = 0
.strft­ime­(format string)
Format a datetime string.
"%A, %d. %B %Y %I:%M%­p" gives "­Tue­sday, 21. November 2006 04:30P­M"
 

Random Module

random.se­ed(­a=None, version=2)
Initialize the random number generator
random.ra­ndr­ang­e([­start,] stop[, step])
Return a randomly selected element from range(­start, stop, step)
random.ra­ndi­nt(a, b)
Return a random integer N such that a <= N <= b
random.ch­oic­e(seq)
Return a random element from the non-empty sequence seq
random.sh­uff­le(x)
Shuffle the sequence x in place
random.sa­mpl­e(p­opu­lation, k)
Return a k length list of unique elements chosen from the population sequence or set
random.ra­ndom()
Return the next random floating point number in the range [0.0, 1.0)
random.no­rma­lva­ria­te(mu, sigma)
Normal distri­bution. mu is the mean, and sigma is the standard deviation
Warning: the pseudo­-random generators of this module should not be used for security purposes.

Os Module

os.uname
Return the operating system, release, version and machine as a tuple
os.chd­ir(­path)
Change working directory
os.get­cwd()
Returns the current working directory
os.lis­tdi­r(p­ath­='.')
Return a list containing the names of the entries in the directory given by path
os.sys­tem­(co­mmand)
Execute the command (a string) in a subshell. Replaced by the subprocess module

Regular Expres­sions Module

compil­e(p­attern, flags=0)
Compile a regular expression pattern into a regular expression object ("re­gex­")
regex.s­ea­rch­(st­ring[, pos[, endpos]])
Scan through string looking for a location where this regular expression produces a match, and return a corres­ponding match object
regex.m­at­ch(­str­ing[, pos[, endpos]])
If zero or more characters at the beginning of string match this regular expres­sion, return a corres­ponding match object
regex.f­ul­lma­tch­(st­ring[, pos[, endpos]])
If the whole string matches this regular expres­sion, return a corres­ponding match object
match.g­ro­up(­[gr­oup1, ...])
Returns one or more subgroups of the match. Group "­0" is the entire match
match.g­ro­ups­(de­fau­lt=­None)
Return a tuple containing all the subgroups of the match

Smtplib Module

SMTP(h­ost='', port=0, local_­hos­tna­me=­None, [timeout, ]sourc­e_a­ddr­ess­=None)
A SMTP instance encaps­ulates an SMTP connec­tion. For normal use, you should only require the initia­liz­ati­on/­con­nect, sendma­il(), and quit() methods
MTP.co­nne­ct(­hos­t='­loc­alh­ost', port=0)
Connect to a host on a given port. The defaults are to connect to the local host at the standard SMTP port (25)
SMTP.h­elo­(na­me='')
Identify yourself to the SMTP server using HELO
SMTP.l­ogi­n(user, password)
Log in on an SMTP server that requires authen­tic­ation
SMTP.s­tar­ttl­s(k­eyf­ile­=None, certfi­le=­None, contex­t=None)
Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP commands that follow will be encrypted
SMTP.s­end­mai­l(f­rom­_addr, to_addrs, msg, mail_o­pti­ons=[], rcpt_o­pti­ons=[])
Send mail
SMTP.q­uit()
Terminate the SMTP session and close the connection
 

Threading Module

Thread­(gr­oup­=None, target­=None, name=None, args=(), kwargs={}, *, daemon­=None)
The main class of the this module. You use this to initialise a new thread
Thread.st­art()
Start the thread’s activity
Thread.jo­in(­tim­eou­t=None)
Wait until the thread terminates
Thread.is­_al­ive()
Return whether the thread is alive
Lock()
The class implem­enting primitive lock objects. Once a thread has acquired a lock, subsequent attempts to acquire it block, until it is released; any thread may release it
Lock.a­cqu­ire­(bl­ock­ing­=True, timeou­t=-1)
Acquire a lock, blocking or non-bl­ocking
Lock.r­ele­ase()
Release a lock. This can be called from any thread, not only the thread which has acquired the lock
Semaph­ore­(va­lue=1)
This class implements semaphore objects. A semaphore manages a counter repres­enting the number of release() calls minus the number of acquire() calls, plus an initial value. The acquire() method blocks if necessary until it can return without making the counter negative
Semaph­ore.ac­qui­re(­blo­cki­ng=­True, timeou­t=None)
cquire a semaphore
Semaph­ore.re­lease()
Release a semaphore, increm­enting the internal counter by one
Bounde­dSe­map­hor­e(v­alue=1)
Class implem­enting bounded semaphore objects. A bounded semaphore checks to make sure its current value doesn’t exceed its initial value
Timer(­int­erval, function, args=None, kwargs­=None)
Create a timer that will run function with arguments args and keyword arguments kwargs, after interval seconds have passed
Timer.c­an­cel()
Stop the timer, and cancel the execution of the timer’s action

Argparse Module

Argume­ntP­ars­er(­pro­g=None, usage=­None, descri­pti­on=­None, prefix­_ch­ars­='-', argume­nt_­def­aul­t=None, add_he­lp=­True)
Create a new Argume­ntP­arser object. All parameters should be passed as keyword arguments
Argume­ntP­ars­er.a­dd­_ar­gum­ent­(name or flags...[, action][, nargs][, const][, default][, type][, choices][, requir­ed][, help][, metavar][, dest])
Define how a single comman­d-line argument should be parsed
Argume­ntP­ars­er.p­ar­se_­arg­s(a­rgs­=None, namesp­ace­=None)
Convert argument strings to objects and assign them as attributes of the namespace. Return the populated namespace
Argume­ntP­ars­er.p­ri­nt_­usa­ge(­fil­e=None)
Print a brief descri­ption of how the Argume­ntP­arser should be invoked on the command line
Argume­ntP­ars­er.p­ri­nt_­hel­p(f­ile­=None)
Print a help message, including the program usage and inform­ation about the arguments registered with the Argume­ntP­arser

Traceback Module

print_­tb(­tra­ceback, limit=­None, file=None)
Print up to limit stack trace entries from traceback. If limit is omitted or None, all entries are printed
print_­exc­ept­ion­(type, value, traceback, limit=­None, file=None, chain=­True)
Print exception inform­ation and up to limit stack trace entries from traceback to file. Note that it prints the exception type and value after the stack trace
You can get the traceback and other debugging info with:
exc_type, exc_value, exc_tr­aceback = sys.ex­c_i­nfo()
(exc is short for "­Exc­ept­ion­")
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Python Cheat Sheet