Skip to content

Instantly share code, notes, and snippets.

@lambdamusic
lambdamusic / Snipplr-25250.py
Created Feb 7, 2013
Python: Python: error handling
View Snipplr-25250.py
## Error handling in Python is done through the use of exceptions that are caught in try blocks and handled in except blocks. If an error is encountered, a TRy block code execution is stopped and transferred down to the except block, as shown in the following syntax:
try:
f = open("test.txt")
except IOError:
print "Cannot open file."
## In addition to using an except block after the try block, you can also use the finally block. The code in the finally block will be executed regardless of whether an exception occurs.
f = open("test.txt")
@lambdamusic
lambdamusic / Snipplr-25272.py
Created Feb 7, 2013
Python: Python: Introspection function
View Snipplr-25272.py
def info(object, spacing=10, collapse=1):
"""Print methods and doc strings.
Takes module, class, list, dictionary, or string."""
methodList = [method for method in dir(object) if callable(getattr(object, method))]
processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
print "\n".join(["%s %s" %
(method.ljust(spacing),
processFunc(str(getattr(object, method).__doc__)))
for method in methodList])
@lambdamusic
lambdamusic / Snipplr-25247.py
Created Feb 7, 2013
Python: Python: PLATFORM module
View Snipplr-25247.py
## The platform module provides a portable interface to information about the platform on which the program is being executed. ## The following examples illustrate some of the most common uses of the platform module.
## The platform.architecture() function returns the (bits, linkage) tuple that specifies the number of bits for the system word size and linkage information about the Python executable:
>>>print platform.architecture()
('32bit', '')
##The platform.python_version() function returns the version of the Python executable for compatibility purposes:
>>>print platform.python_version()
@lambdamusic
lambdamusic / Snipplr-26620.py
Created Feb 7, 2013
Python: Python: simple REgex example
View Snipplr-26620.py
>>> s
'1/Mar/1215'
>>> pattern = r"(\d+)"
>>> re.match(pattern, s).groups()
('1',)
>>> pattern = r"(\d+)/(Sept|Mar)/(\d+)"
>>> re.match(pattern, s).groups()
('1', 'Mar', '1215')
@lambdamusic
lambdamusic / Snipplr-25249.py
Created Feb 7, 2013
Python: Python: OS module
View Snipplr-25249.py
# The os module provides a portable platform-independent interface to access common operating services,
# allowing you to add OS-level support to your programs.
# The os.path.abspath(path) function of the os module returns a string version of the absolute path of the
# path specified. Because abspath takes into account the current working directory, the . and .. directory
# options will work as shown next:
>>>print os.path.abspath(".")
>>>C:\books\python\ch1\ print os.path.abspath("..") C:\books\python\
@lambdamusic
lambdamusic / Snipplr-46831.py
Created Feb 7, 2013
Python: Python generator
View Snipplr-46831.py
def generate_ints(N):
for i in range(N):
yield i
>>> gen = generate_ints(3)
>>> gen
<generator object at 0x8117f90>
>>> gen.next()
0
View Snipplr-29633.py
import MySQLdb
conn = MySQLdb.connect(host=\"localhost\", user=\"root\", passwd=\"nobodyknow\", db=\"amit\")
cursor = conn.cursor()
stmt = \"SELECT * FROM overflows\"
cursor.execute(stmt)
# Fetch and output
result = cursor.fetchall()
@lambdamusic
lambdamusic / Snipplr-25246.py
Created Feb 7, 2013
Python: Python: TIME module
View Snipplr-25246.py
## The time module provides a portable interface to time functions on the system on which the program is executing. The following examples illustrate some of the most common uses of the time module.
##The time.time() function returns the current system time in terms of the number of seconds since the UTC (Coordinated Universal Time). This value is typically collected at various points in the program and is used in delta operations to determine the amount of time since an event occurred.
>>>print time.time()
1155333864.11
##The time.localtime(secs) function returns the time, specified by secs since the UTC, in the form of tuple (year, month, day, hour, minute, second, day of week, day of year, daylight savings). If no time is specified, the current time is used as follows:
>>>print time.localtime()
(2006, 8, 11, 16, 4, 24, 4, 223, 1)
@lambdamusic
lambdamusic / Snipplr-25262.py
Created Feb 7, 2013
Python: Python: formatting strings
View Snipplr-25262.py
>>>list = ["Brad", "Dayley", "Python Phrasebook",
2006]
>>>letter = """
>>>Dear Mr. %s,\n
>>>Thank you for your %s book submission.
>>>You should be hearing from us in %d."""
>>>display = """
>>>Title: %s
@lambdamusic
lambdamusic / Snipplr-25248.py
Created Feb 7, 2013
Python: Python: SYS module
View Snipplr-25248.py
# The sys module provides an interface to access the environment of the Python interpreter.
# The following examples illustrate some of the most common uses of the sys module.
# The argv attribute of the sys module is a list. The first item in the argv list is the
# path to the module; the rest of the list is made up of arguments that were passed to the
# module at the beginning of execution. The sample code shows how to use the argv list to
# access command-line parameters passed to a Python module:
>>>print sys.argv
['C:\\books\\python\\CH1\\code\\print_it.py',