ITTips
PythonTips
Install MySQLdb connector on Mac OSX
To install the python/
MySQL connector on Mac OS X follow the following tutorials:
Cast
To cast to string type:
i=0
print str(i)
Length of an array
myArray=[]
len(myArray)
MySQL connection
You have to create a cursor to connect to the database.
The cursor is created with
MySQLdb.connect.
Then in the cursor class, you have a couple of methods:
- execute(): to execute a mysql query
- rowcount(): will return the number of lines of your sql query
- fetchall(): get all the results from your sql query
- fetchone(): method used to move forward through the resultset
2 ways to create sql queries and execute them:
sqlInsert = "insert into servers set servername='%s',location='%s',purpose='%s',live='%s',coderelease='%s'" % (servername,location,purpose,live,coderelease)
cursor.execute(sqlInsert)
cursor.execute("insert into servers set servername='%s',location='%s',purpose='%s',live='%s',coderelease='%s'" , (servername,location,purpose,live,coderelease))
The 1st one being the neater!
methods definition
When defining your class methods, you must explicitly list self as the first argument for each method, including
init
built in functions
http://docs.python.org/lib/built-in-funcs.html∞
Python Editor
SPE. To install it on mac, you need the python framework and wxpython:
http://www.wxpython.org∞
If you want to change the way shortcut are bound on your keyboard please check this post:
https://lists.berlios.de/pipermail/python-spe-dev/2005-December/000075.html∞
Basically, shortcuts are defined in
Contents/Resources/_spe/shorcuts/OS.py
Sending emails in HTML with attached documents
http://code.activestate.com/recipes/473810/∞
String functions
text=text.encode(charset,'replace')
More info:
http://docs.python.org/lib/string-methods.html∞
charset definition:
http://docs.python.org/lib/standard-encodings.html∞
use SSH with python
http://www.noah.org/wiki/Pexpect∞
Parse the input of a CLI script
http://docs.python.org/library/optparse.html∞
Not showing the password
import getpass
password = getpass.getpass('Password: ')
Nested dictionaries
http://old.nabble.com/creating-a-nested-dictionary-td15061183.html∞
def deep_default_dict(level):
"""
This has been done to implement dict with several depths.
http://old.nabble.com/creating-a-nested-dictionary-td15061183.html
"""
if level < 1:
raise ValueError()
result = dict
while level > 1:
result = lambda: defaultdict(result)
level -= 1
return result
To do so, we need to juggle with default dictionary
There are no comments on this page. [Add comment]