#open your .bash_profile by typing this into Terminal. You'll need to be in your home directory. sudo mate edit .bash_profile # Paste something like this into your .bash_profile export PYTHONPATH=$HOME/Sites/dev:$PYTHONPATH
Tag Archive for python
Add a directory to your PYTHONPATH in Terminal.app using TextMate
Python ldap
import ldap LDAP_ADDR = 'ldap.daimi.au.dk' LDAP_CONFIG = 'uid=%s,ou=people,dc=daimi,dc=au,dc=dk' def checkPassword(username, password): server = LDAP_ADDR l = ldap.open(server) if password == "": password = "wrong" try: l.simple_bind_s(LDAP_CONFIG % username, password) except: return False return True
Equação do segundo grau
#!/usr/bin/python # Criado em:Dom 12/Ago/2007 hs 10:49 # Last Change: Dom 12 Ago 2007 11:11:06 BRT # Instituicao: import math class Raizes: def __init__(self, a, b, c): #construtores self.a = a self.b = b self.c = c self.delta = self.b**2 - 4 * self.a * self.c def calcula_Raizes(self): #metodo_de_calculo_das_raizes if self.delta < 0: print "Delta negativo:ndelta: %f" %(self.delta) elif self.delta == 0: self.xxx = (-self.b + math.sqrt(self.delta)) / 2*self.a print "Valor Calculado.nx: %fndelta: %f" %(self.xxx, self.delta) elif self.delta > 0: self.x = (-self.b + math.sqrt(self.delta)) / 2*self.a self.xx = (-self.b - math.sqrt(self.delta)) / 2*self.a print "Raizes.nx: %fnxx: %fndelta: %f" %(self.x, self.xx, self.delta)
Get Day Suffix
def getDaySuffix(dayNumber):
if dayNumber <= 3:
return {1:"st", 2:"nd", 3:"rd"}[dayNumber]
else:
return "th"
# ex: June 12th
nowTime = datetime.datetime.now()
print nowTime.strftime("%B %d" + getDaySuffix(nowTime.timetuple()[2]))
Python Datetime Usage
import datetime
# ex: 09-06-12-10-01
print datetime.datetime.now().strftime("%y-%m-%d-%H-%M")
Four Char Code From String in Python
def makeNumberFromCharCode(code):
return (ord(code[0]) << 24) | (ord(code[1]) << 16) | (ord(code[2]) << <img src='http://www.snippetsmania.com/wp-includes/images/smilies/icon_cool.gif' alt='8)' class='wp-smiley' /> | ord(code[3])
# In Carbon / Cocoa:
# FourCharCode code = 'abcd'
# In Python:
# code = makeNumberFromCharCode("abcd")
handler for http post
Python Handlers
This is the python script that handles requests to the endpoints defined above. This file is located at $SPLUNK_HOME/etc/apps/WebSkunk/rest/webskunkhandlers.py.
#
# http request handlers
#
from splunk import auth, search
import splunk.rest
import utils
import logging as logger
import splunk.bundle as bundle
import httplib2, urllib, os, time
import telnetlib
# set our path to this particular application directory (which is suppose to be <appname>/bin)
app_dir = os.path.dirname(os.path.abspath(__file__))
# define the web content directory (needs to be <appname>/web directory)
web_dir = app_dir + "/web"
class main(splunk.rest.BaseRestHandler):
'''
Main endpoint
'''
def handle_GET(self):
# set output params
self.response.setStatus(200)
self.response.setHeader('content-type', 'text/html')
self.response.write('Main: this is webskunk')
# listen to all verbs
handle_POST = handle_DELETE = handle_PUT = handle_VIEW = handle_GET
class status(splunk.rest.BaseRestHandler):
'''
Status endpoint
'''
def handle_GET(self):
# set output params
self.response.setStatus(200)
self.response.setHeader('content-type', 'text/html')
self.response.write('<html><head><title>webskunk</title></head><body>')
self.response.write('<h1>Status: webskunk is online</h1><br><br>')
self.response.write('<b>Active endpoints:</b><br>')
self.response.write(utils.getHrefs(self.pathParts[1]))
self.response.write('</body></html>')
# listen to all verbs
handle_POST = handle_DELETE = handle_PUT = handle_VIEW = handle_GET
class web(splunk.rest.BaseRestHandler):
'''
Main endpoint
'''
def handle_GET(self):
files = []
logger.debug('scanning %s' % web_dir)
# do a scan of the application directory's web directory
for root, dirs, file_list in os.walk(web_dir):
cur_dir = root.replace(web_dir, '')
for file in file_list:
full_name = os.path.join(cur_dir, file)
files.append(full_name)
# extract the last segment of the URL passed to splunkd and use it to load a file
last_segment = self.pathParts[len(self.pathParts)-1]
# check the requested file exists in the web directory - if not, we return a 404
if last_segment in files:
f = open(web_dir + '/' + last_segment, 'rb')
content = f.read()
f.close()
# basic checking of file extension to set a mime type
if ".html" in last_segment:
self.response.setHeader('content-type', 'text/html')
elif ".js" in last_segment:
self.response.setHeader('content-type', 'application/x-javascript')
elif ".css" in last_segment:
self.response.setHeader('content-type', 'text/css')
elif ".jpg" in last_segment:
# this won't work for now - leaving here for a reminder
self.response.setHeader('content-type', 'image/jpeg')
content_length = "%d" % len(content)
self.response.setHeader('Content-Length', content_length)
self.response.setStatus(200)
else:
self.response.setStatus(404)
content = "404 - not found!"
self.response.write(content)
class receiver(splunk.rest.BaseRestHandler):
def handle_POST(self):
host="localhost"
tn = telnetlib.Telnet(host, 9998)
try:
content = self.args['splunkdata']
tn.write(content)
self.response.write("AWESOME!")
except Exception, e:
logger.exception(e)
self.response.write(e)
# listen to all verbs
handle_GET = handle_DELETE = handle_PUT = handle_VIEW = handle_POST
geocode address via urllib
import urllib,urllib2,time
addr_file = 'addresses.csv'
out_file = 'addresses_geocoded.csv'
out_file_failed = 'failed.csv'
sleep_time = 2
root_url = "http://maps.google.com/maps/geo?"
gkey = "YourGoogleKeyGoesHere"
return_codes = {'200':'SUCCESS',
'400':'BAD REQUEST',
'500':'SERVER ERROR',
'601':'MISSING QUERY',
'602':'UNKOWN ADDRESS',
'603':'UNAVAILABLE ADDRESS',
'604':'UNKOWN DIRECTIONS',
'610':'BAD KEY',
'620':'TOO MANY QUERIES'
}
def geocode(addr,out_fmt='csv'):
#encode our dictionary of url parameters
values = {'q' : addr, 'output':out_fmt, 'key':gkey}
data = urllib.urlencode(values)
#set up our request
url = root_url+data
req = urllib2.Request(url)
#make request and read response
response = urllib2.urlopen(req)
geodat = response.read().split(',')
response.close()
#handle the data returned from google
code = return_codes[geodat[0]]
if code == 'SUCCESS':
code,precision,lat,lng = geodat
return {'code':code,'precision':precision,'lat':lat,'lng':lng}
else:
return {'code':code}
def main():
#open our i/o files
outf = open(out_file,'w')
outf_failed = open(out_file_failed,'w')
inf = open(addr_file,'r')
for address in inf:
#get latitude and longitude of address
data = geocode(address)
#output results and log to file
if len(data)>1:
print "Latitude and Longitude of "+address+":"
print " Latitude:",data['lat']
print " Longitude:",data['lng']
outf.write(address.strip()+data['lat']+','+data['lng']+'
')
outf.flush()
else:
print "Geocoding of '"+addr+"' failed with error code "+data['code']
outf_failed.write(address)
outf_failed.flush()
#play nice and don't just pound the server with requests
time.sleep(sleep_time)
#clean up
inf.close()
outf.close()
outf_failed.close()
if __name__ == "__main__":
main()
urllib2 http post
#!/usr/bin/python
import urllib,urllib2
url = 'http://www.commentcamarche.net/search/search.php3'
parameters = {'Mot' : 'Gimp'}
data = urllib.urlencode(parameters) # Use urllib to encode the parameters
request = urllib2.Request(url, data)
response = urllib2.urlopen(request) # This request is sent in HTTP POST
page = response.read(200000)