Python

From Robertjd

Jump to: navigation, search

Contents

[hide]

URL Parsing

To turn a GET parameter like this into a dict:

loginurl=http%3a%2f%2f10.1.1.20%3a8000%2flogin%3fres%3dnotyet%26uamip%3d10.1.0.1%26uamport%3d3660%26challenge%3d8cf43e12058e2daeebb33f0b24ebdc16%26mac%3d00-15-AF-78-01-01%26ip%3d10.1.0.5%26called%3d00-12-17-12-35-3E%26nasid%3d00-12-17-12-35-3E%26userurl%3dhttp%253a%252f%252fwww.debian.org%252f%26md%3d59524896971619C0DF2BF52A052260DC

Do this:

from urllib import unquote
from cgi import parse_qsl
loginurl = dict(parse_qsl(unquote(request.GET['loginurl']).split('?')[1]))

See: http://www.nabble.com/urldecode-function--td18985140.html

Time

Simpler - with time
>>> time.time()
1223664255.652807
>>> int(time.time())
1223664262

GMT Time
>>> datetime.datetime.utcnow().strftime('%F %H:%M:%S')
'2008-09-10 18:14:28'
>>> datetime.datetime.utcnow().strftime('%s')
'1221095680'

Local (example: pacific) Time
>>> datetime.datetime.now().strftime('%F %H:%M:%S')
'2008-09-10 11:16:18'
>>> datetime.datetime.now().strftime('%s')
'1221070572'

Replacing tabs with spaces

This perl expression will replace tabs with two spaces (as tried on my mac):

perl -e '($_ = join "",<>) =~ s/(\t)/  /g; print;' < test.py > test.new.py

Found here: http://forums.devshed.com/unix-help-35/replacing-tabs-with-spaces-372623.html

String Formatting

>>> print "%04d" % n
0002

Learning

http://openbookproject.net//thinkCSpy/

http://www.greenteapress.com/thinkpython/thinkpython.html

Personal tools