Posted by hide1713 on November 20, 2009
In [71]: m=10
In [72]: i=[3,4]
In [73]: j=[m for m in i]
In [74]: j
Out[74]: [3, 4]
In [75]: m
Out[75]: 4
Notice that the value of m changed from 10 to 4 and it’s not my intention.!!
Next time when you write [x for x in y]. Make sure x is unused!!!
Posted in Python | Leave a Comment »
Posted by hide1713 on June 1, 2009
This wonderful tiny tool give you the ability to run program in XP & Vista background. It helps me hide the cmd.exe window so that I can run my python wiki server complete in the background.
hstart home page and download:
http://www.ntwind.com/software/utilities/hstart.html
Usage:
hstart /NOCONSOLE “whatever command you want”
Posted in Python | Leave a Comment »
Posted by hide1713 on January 25, 2009
I want to search google in python so I spent few hours to find out a solution. First, I looked for pygoole module. Soon, I found that google didn’t provide license for SOAP anymore. I can’t use any module based on SOAP servies. However, google provides Ajax api for web searching. Here are two links which inspired me: post1 and post2
The problem for Ajax API is that the maximum result for each keyword is 64. However, If you need a simple interface to search google in python. The following code may help you.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__="Lei Chen <hide1713@gmail.com>"
import urllib2
def search_google(keyword,result_num):
"""return: A list of result url. The result_num must be smaller than 64
since google only provides 64 results for every keyword
Arguments:
- `keyword`: search keyword ex. "google", "video game"
- `result_num`: [0-64]
>>> search_google("indiana university",2)
['http://www.indiana.edu/', 'http://www.iub.edu/']
"""
i=0
results=[]
start=[0, 8, 16, 24, 32, 40, 48, 56, 64]
if result_num>64:
result_num=64
while start[i]<result_num:
url = "http://ajax.googleapis.com/ajax/services/search/web\
?v=1.0&start=%d&rsz=large&q=%s"%(start[i],keyword.replace(" ","%20"))
req = urllib2.Request(url)
opener = urllib2.build_opener()
data = opener.open(req).read()
# replace the "null" with "None" for Python
data = data.replace(": null,", ": None,")
# convert the string to a dictionary
exec("data = " + data)
# simplify the results a bit
results += data["responseData"]["results"]
i+=1
# remove extra url records.
extra_url = start[i] - result_num
# only need url filed
url_results=[i["url"] for i in results[:-extra_url]]
return url_results
#if __name__ == '__main__':
# import doctest
# doctest.testmod()
if __name__ == '__main__':
results=search_google("indiana university", 50 )
j=1
for i in results:
print j,":",i
j+=1
Posted in Python | Leave a Comment »
Posted by hide1713 on January 12, 2009
As we all know, bug-free coding is hard to achieve. Python makes test remarkably easy and convenient with doctest module which reduces low level bugs by putting test code right into doc string. The major benefits of doctest are:
1. It’s easy to write. You don’t need to switch back and forth between unit test file and your source code. All test codes are written in doc string.
2.It improve the readability of doc string. I use doctest for cases where the test is giving an example of usage that is actually useful as documentation.
3.It helps you refine the design. When you are working on some “fast and dirty” code”, you should consider writhing doctest for your function. By writhing test, you have to think about the realation between functions. You have to find out the answer about: what is the responsibility of this function and who should call this function?
Here is my doctest sample file. The file name is mydoctest.py
def max(a,b):
"""Returen the big one
>>> max(2,3)
3
"""
if a>b:
return a
else:
return b
if __name__=="__main__":
import doctest
doctest.testmod()
Notice! There must be a space after >>>. You can run the test by calling
python mydoctest.py -v
You need to add -v at the end of this command. Otherwise, you will see nothing form output. The result looks like this:
Trying:
max(2,3)
Expecting:
3
ok
1 items had no tests:
__main__
1 items passed all tests:
1 tests in __main__.max
1 tests in 2 items.
1 passed and 0 failed.
Test passed.
Posted in Python | Leave a Comment »
Posted by hide1713 on November 7, 2008
This code downloads yahoo xml weather forecast data and draws it on north east side of a picture
you can create a script like this
#!/bin/bash
sleep 25 && /home/hide1713/python_project/get_weather.py -c -i
/home/hide1713/Pictures/lamp.jpg -z 47408
then use chmod +x to make it executable, add this script in your start session.
It will create a new picture “pciture_name_new”, use this picture as your wallpaper.
NOTE: This script need lxml packet.
#!/usr/bin/env python
"""
Weather Forecast to wallpaper
By Lei Chen (hide1713 at gmail dot com)
This program reads xml data from yahoo then uses convert command to write a string on wallpaper
"""
from lxml import etree
import urllib2,os,getopt,sys
picture_name=''
zipcode=''
f_or_c='c'
args=sys.argv[1:]
def usage ():
""""""
print """Weather Forecast Wallpaper:
Usage:
-i <wallpaper file name>
-[f|c] : Fahrenheit/Celius
-z : Your zipcode
"""
try:
opts,args=getopt.getopt(args,'z:fci:')
except getopt.GetoptError, err:
# print help information and exit:
print str(err) # will print something like "option -a not recognized"
usage()
sys.exit(2)
for o,a in opts:
if o=="-c":
f_or_c='c'
if o=='-f':
f_or_c='f'
if o=="-i":
picture_name=a
if o=='-z':
try:
zipcode=int(a)
except:
print "zip code must be a number"
sys.exit(2)
if not os.access(picture_name,os.W_OK):
print "Can not write picture"
usage()
sys.exit(1)
if zipcode=='':
print "No zipcode?"
sys.exit(1)
print "Generating ",zipcode," weather forecast to ",picture_name
req=urllib2.Request("http://weather.yahooapis.com/forecastrss?p=%d&u=%s"%(zipcode,f_or_c))
fd = urllib2.urlopen(req)
tree=etree.fromstring(fd.read(),base_url="http://weather.yahooapis.com/forecastrss?p=47408")
s=''
for ele in tree.iter():
if ele.tag=='{http://xml.weather.yahoo.com/ns/rss/1.0}forecast':
s+=ele.attrib['day']+" "+ele.attrib['low']+"-"+ele.attrib['high']
s+=" "+ele.attrib['text']+" "
os.popen("""convert %s -pointsize 24 -draw "gravity NorthEast fill white text 0,12'%s'" %s"""%(picture_name,s,picture_name[:-4]+"_new"+picture_name[-4:]))
Posted in Python | Tagged: getopt, Python, xml | Leave a Comment »