You are on page 1of 3

Intermediate Python Cheat Sheet

by Mr Kitty via cheatography.com/23005/cs/4937/

Built-in Functions JSON Module (cont) Datetime Module

float() int() loads(s, Deserialize s (a str instance datetime.date() An idealized date

bin(num) hex(num) [same containing a JSON document) datetime.time() An idealized time


arguments as to a Python object
dict() list() datetime.datetime(year, A combination of
dumps])
month, day, hour=0, time and date
tuple() str()
JSON functions have a lot of arguments, you'll minute=0, second=0,
complex(a, b) bool(x) only need to use "obj", "fp", and "s" about 99% microsecond=0,
set() sorted(s) of the time though tzinfo=None)
bytes(s) bytearray(s) datetime.timedelta(days=0, A time difference
Subprocess Module
abs(num) len(s) seconds=0,
subprocess.run(ar The recommended microseconds=0,
max(s) min(s)
gs, *, approach to invoking milliseconds=0,
ord(char) chr(num) minutes=0, hours=0,
stdin=None, subprocesses. This does
pow(x,y) range([start] : stop : input=None, not capture stdout or weeks=0)
[step]) stdout=None, stderr by default. To do datetime.today() Return the current
round(num, places) sum(s) stderr=None, so, pass day
shell=False, subprocess.PIPE to the
open(filename, type(obj) datetime.now(tz=None) Return the current
timeout=None, appropriate arguments
[mode]) time and date
check=False)
id(obj) divmod(num, divisor) datetime.date() Return the date
subprocess.call(ar Run the command
portion of a
input(prompt) print(s) gs, *, described by args. Wait
datetime object
stdin=None, for command to complete,
JSON Module stdout=None, then return the returncode datetime.time() Return the time
portion of a
stderr=None, attribute
dump(obj, fp, Serialize obj as datetime object
shell=False,
skipkeys=False, a JSON
timeout=None) datetime.weekday() Return the day of
ensure_ascii=True, formatted
the week. Monday
check_circular=True, stream to fp (a subprocess.check Run command with
_output(**) arguments and return its =0
allow_nan=True, cls=None, .write()-supporti
indent=None, ng file-like output. Same as run(..., .strftime(format string) Format a datetime

separators=None, object) check=True, string.

default=None, stdout=PIPE).stdout "%A, %d. %B %Y


sort_keys=False, **kw) %I:%M%p" gives
Note that "**" means to use the same
"Tuesday, 21.
dumps([same arguments as Serialize obj to arguments as above
November 2006
above, minus "fp"]) a JSON
04:30PM"
formatted str Time Module

load([same as dump]) Deserialize fp time.cl On Unix, return the current processor Random Module
(a .read()-
ock() time as a floating point number
supporting file- random.seed(a= Initialize the random number
expressed in seconds
like object None, generator
time.sl Suspend execution of the calling version=2)
containing a
eep(se thread for the given number of
JSON random.randran Return a randomly selected
cs) seconds
document) to a ge([start,] stop[, element from range(start,
Python object step]) stop, step)

random.randint( Return a random integer N


a, b) such that a <= N <= b

By Mr Kitty Published 19th August, 2015. Sponsored by CrosswordCheats.com


cheatography.com/mr-kitty/ Last updated 19th August, 2015. Learn to solve cryptic crosswords!
Page 1 of 3. http://crosswordcheats.com
Intermediate Python Cheat Sheet
by Mr Kitty via cheatography.com/23005/cs/4937/

Random Module (cont) Regular Expressions Module Smtplib Module (cont)

random.choi Return a random element from compile( Compile a regular expression MTP.connect(hos Connect to a host on a
ce(seq) the non-empty sequence seq pattern, pattern into a regular expression t='localhost', given port. The defaults are
flags=0) object ("regex") port=0) to connect to the local host
random.shuf Shuffle the sequence x in place
at the standard SMTP port
fle(x) regex.sea Scan through string looking for a
(25)
rch(string location where this regular
random.sam Return a k length list of unique
ple(populatio elements chosen from the [, pos[, expression produces a match, and SMTP.helo(name Identify yourself to the

n, k) population sequence or set endpos]]) return a corresponding match ='') SMTP server using HELO
object
SMTP.login(user, Log in on an SMTP server
random.rand Return the next random floating
regex.ma If zero or more characters at the password) that requires
om() point number in the range [0.0,
tch(string beginning of string match this authentication
1.0)
[, pos[, regular expression, return a SMTP.starttls(ke Put the SMTP connection
random.nor Normal distribution. mu is the
endpos]]) corresponding match object yfile=None, in TLS (Transport Layer
malvariate( mean, and sigma is the standard
mu, sigma) deviation regex.full If the whole string matches this certfile=None, Security) mode. All SMTP
match(str regular expression, return a context=None) commands that follow will
Warning: the pseudo-random generators of this ing[, corresponding match object be encrypted
module should not be used for security pos[, SMTP.sendmail(f Send mail
purposes. endpos]]) rom_addr,
match.gr Returns one or more subgroups of to_addrs, msg,
Os Module
oup([grou the match. Group "0" is the entire mail_options=[],
os.uname Return the operating system, p1, ...]) match rcpt_options=[])
release, version and machine as a match.gr Return a tuple containing all the SMTP.quit() Terminate the SMTP
tuple oups(defa subgroups of the match session and close the
os.chdir(p Change working directory ult=None connection
ath) )

os.getcwd Returns the current working Threading Module

() directory Smtplib Module


Thread(group=None, The main class of
os.listdir( Return a list containing the names SMTP(host='', A SMTP instance target=None, the this module.
path='.') of the entries in the directory given port=0, encapsulates an SMTP name=None, args=(), You use this to
by path local_hostnam connection. For normal use, kwargs={}, *, initialise a new
e=None, you should only require the daemon=None) thread
os.system Execute the command (a string) in
[timeout, initialization/connect, Thread.start() Start the threads
(comman a subshell. Replaced by the
]source_addres sendmail(), and quit() activity
d) subprocess module
s=None) methods
Thread.join(timeout=Non Wait until the thread
e) terminates

Thread.is_alive() Return whether the


thread is alive

By Mr Kitty Published 19th August, 2015. Sponsored by CrosswordCheats.com


cheatography.com/mr-kitty/ Last updated 19th August, 2015. Learn to solve cryptic crosswords!
Page 2 of 3. http://crosswordcheats.com
Intermediate Python Cheat Sheet
by Mr Kitty via cheatography.com/23005/cs/4937/

Threading Module (cont) Threading Module (cont) Argparse Module (cont)

Lock() The class implementing primitive BoundedSe Class implementing bounded Argument Print a brief description of how the
lock objects. Once a thread has maphore(va semaphore objects. A bounded Parser.pri ArgumentParser should be
acquired a lock, subsequent lue=1) semaphore checks to make sure nt_usage(f invoked on the command line
attempts to acquire it block, until it is its current value doesnt exceed ile=None)
released; any thread may release it its initial value
Argument Print a help message, including
Lock.acq Acquire a lock, blocking or non- Timer(inter Create a timer that will run Parser.pri the program usage and
uire(bloc blocking val, function with arguments args nt_help(fil information about the arguments
king=Tr function, and keyword arguments kwargs, e=None) registered with the
ue, args=None, after interval seconds have ArgumentParser
timeout= kwargs=No passed
-1) ne) Traceback Module
Lock.rel Release a lock. This can be called Timer.canc Stop the timer, and cancel the
print_tb(traceb Print up to limit stack trace
ease() from any thread, not only the thread el() execution of the timers action
ack, entries from traceback. If limit
which has acquired the lock
limit=None, is omitted or None, all entries
Semaph This class implements semaphore Argparse Module file=None) are printed
ore(valu objects. A semaphore manages a
ArgumentParser(prog= Create a new print_exceptio Print exception information
e=1) counter representing the number of
None, usage=None, ArgumentParser n(type, value, and up to limit stack trace
release() calls minus the number of
description=None, object. All traceback, entries from traceback to file.
acquire() calls, plus an initial value.
prefix_chars='-', parameters should limit=None, Note that it prints the
The acquire() method blocks if
argument_default=None, be passed as file=None, exception type and value after
necessary until it can return without
add_help=True) keyword arguments chain=True) the stack trace
making the counter negative
ArgumentParser.add_ar Define how a single You can get the traceback and other debugging
Semaph cquire a semaphore
gument(name or flags... command-line info with:
ore.acqu
[, action][, nargs][, argument should be exc_type, exc_value, exc_traceback =
ire(block
const][, default][, type][, parsed sys.exc_info()
ing=Tru
choices][, required][, (exc is short for "Exception")
e,
help][, metavar][, dest])
timeout=
None) ArgumentParser.parse_ Convert argument
args(args=None, strings to objects
Semaph Release a semaphore,
namespace=None) and assign them as
ore.relea incrementing the internal counter by
attributes of the
se() one
namespace. Return
the populated
namespace

By Mr Kitty Published 19th August, 2015. Sponsored by CrosswordCheats.com


cheatography.com/mr-kitty/ Last updated 19th August, 2015. Learn to solve cryptic crosswords!
Page 3 of 3. http://crosswordcheats.com

You might also like