Saturday, February 28, 2009

自己用Python写的一个图像格式转换器 (2006-10-12 17:3...



自己用Python写的一个图像格式转换器 (2006-10-12 17:30:09)



今天同时需要把大量的JPG格式图片转换成BMP的,找了些软件都是有试用期的。我灵机一动: 为啥不自己写一个批量图片格式转换器那? 于是有了下面的东西。



  把这个脚本放到存放图像文件的目录下。输入python covimage.py 源格式,目标格式就可以了。



转换完后文件名不变,扩展名变了。



另外需要PIL这个库,太大传不上来,可以到



http://www.pythonware.com/products/pil/



下载。 现在还需要Python环境才能工作,我准备把它作成一个。EXE的文件,直接执行就可以了。





源代码:





--*-- coding:gb2312  --*--



# code by whl



import Image

import os

import sys





if len(sys.argv) != 3:

    print "Usage python covimage.py source_type target_type"

    sys.exit()

   

arg="."+sys.argv[1]

arg1="."+sys.argv[2]



#*********** 获取当前目录下指定格式的图像文件 **************

def getImageFiles():

    allfiles = os.listdir('.')



    files = []



    for f in allfiles:

        if f[-4:].lower()==arg:

            files.append(f)



    return files

   

#********************* 转换 *******************

def CovImage():

   

    filename=getImageFiles()

    for i in filename:

        x=i[:-4]  



        Image.open(i).save(x+arg1)

    

if __name__ == "__main__":



    CovImage()


Friday, February 27, 2009

如何得到一个路径下的所有子文件夹和子 文件的信息?

发信人: moonson (世界很奇妙,待我去创造), 信区: Python
标  题: 如何得到一个路径下的所有子文件夹和子 文件的信息?
发信站: 水木社区 (Fri Feb 27 14:59:22 2009), 转信

另外,如何判断一个路径是文件夹还是文件?
--
当知汉代的奴隶,并不专是农奴或苦役,奴隶市场出卖的奴婢,多是投入奢侈圈的,并
不是走进劳役阵线的。


※ 来源:·水木社区 http://newsmth.net·[FROM: 210.5.29.*]

发信人: Wanaka (Wanaka), 信区: Python
标  题: Re: 如何得到一个路径下的所有子文件夹和子 文件的信息?
发信站: 水木社区 (Fri Feb 27 15:00:28 2009), 转信


【 在 moonson (世界很奇妙,待我去创造) 的大作中提到: 】
: 标  题: 如何得到一个路径下的所有子文件夹和子 文件的信息?
用os.walk
: 发信站: 水木社区 (Fri Feb 27 14:59:22 2009), 转信
:
: 另外,如何判断一个路径是文件夹还是文件?
用os.path.isfile 和os.path.isdir

--

※ 修改:·Wanaka 于 Feb 27 15:02:14 2009 修改本文·[FROM: 202.120.58.*]
※ 来源:·水木社区 newsmth.net·[FROM: 202.120.58.*]

发信人: moonson (世界很奇妙,待我去创造), 信区: Python
标  题: Re: 如何得到一个路径下的所有子文件夹和子 文件的信息?
发信站: 水木社区 (Fri Feb 27 15:09:55 2009), 转信

多谢
刚才在网上看到一个os.listdir,与os.walk有何区别?

【 在 Wanaka (Wanaka) 的大作中提到: 】
: 用os.walk
: 用os.path.isfile 和os.path.isdir

--
当知汉代的奴隶,并不专是农奴或苦役,奴隶市场出卖的奴婢,多是投入奢侈圈的,并
不是走进劳役阵线的。


※ 来源:·水木社区 http://newsmth.net·[FROM: 210.5.29.*]

发信人: Wanaka (Wanaka), 信区: Python
标  题: Re: 如何得到一个路径下的所有子文件夹和子 文件的信息?
发信站: 水木社区 (Fri Feb 27 15:12:38 2009), 转信

listdir只返回制定目录下的文件和子目录,
walk返回的还有子目录下面的子目录和文件……,递归的。
用os.walk就不用os.listdir然后判断是否为目录进行再次listdir了。
【 在 moonson (世界很奇妙,待我去创造) 的大作中提到: 】
: 标  题: Re: 如何得到一个路径下的所有子文件夹和子 文件的信息?
: 发信站: 水木社区 (Fri Feb 27 15:09:55 2009), 转信
:
: 多谢
: 刚才在网上看到一个os.listdir,与os.walk有何区别?
:
: 【 在 Wanaka (Wanaka) 的大作中提到: 】
: : 用os.walk
: : 用os.path.isfile 和os.path.isdir

--

※ 来源:·水木社区 newsmth.net·[FROM: 202.120.58.*]

发信人: moonson (世界很奇妙,待我去创造), 信区: Python
标  题: Re: 如何得到一个路径下的所有子文件夹和子 文件的信息?
发信站: 水木社区 (Fri Feb 27 15:14:26 2009), 转信

got it thanks

【 在 Wanaka (Wanaka) 的大作中提到: 】
: listdir只返回制定目录下的文件和子目录,
: walk返回的还有子目录下面的子目录和文件……,递归的。
: 用os.walk就不用os.listdir然后判断是否为目录进行再次listdir了。

--
当知汉代的奴隶,并不专是农奴或苦役,奴隶市场出卖的奴婢,多是投入奢侈圈的,并
不是走进劳役阵线的。


※ 来源:·水木社区 http://newsmth.net·[FROM: 210.5.29.*]

发信人: N23 (23号), 信区: Python
标  题: Re: 如何得到一个路径下的所有子文件夹和子 文件的信息?
发信站: 水木社区 (Fri Feb 27 15:44:11 2009), 转信

Shell:~/mylibs/lib/Python/MyPyLib >: cat DirectoryStatWalker.py
#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import os
import stat

class DirectoryStatWalker:
    # a forward iterator that traverses a directory tree, and
    # returns the filename and additional file information

    def __init__(self, directory):
        self.stack = [directory]
        self.files = []
        self.index = 0

    def __getitem__(self, index):
        while 1:
            try:
                file = self.files[self.index]
                self.index = self.index + 1
            except IndexError:
                # pop next directory from stack
                self.directory = self.stack.pop()
                self.files = os.listdir(self.directory)
                self.index = 0
            else:
                # got a filename
                fullname = os.path.join(self.directory, file)
                st = os.stat(fullname)
                mode = st[stat.ST_MODE]
                if stat.S_ISDIR(mode) and not stat.S_ISLNK(mode):
                    self.stack.append(fullname)
                return fullname, st

if __name__ == '__main__':
    for file, st in DirectoryStatWalker("/usr/include"):
        print file, st[stat.ST_SIZE]

【 在 moonson (世界很奇妙,待我去创造) 的大作中提到: 】
: 另外,如何判断一个路径是文件夹还是文件?

Thursday, February 12, 2009

最简单的下载网页的方法
































打印

用python下载网页,超级简单!
















用python下载网页,超级简单!






  1. <br>  
  2. from urllib import urlopen<br>  
  3. <br>  
  4. webdata = urlopen("http://www.<span href="tag.php?name=python" onclick="tagshow(event)" class="t_tag">python</span>id.com").read()<br>  
  5. print webdata<br>  


from urllib import urlopen



webdata = urlopen("http://www.pythonid.com").read()

print webdata



够简单吧,哈哈。










TOP























python最适合干这种事情了!










TOP























我来补充点,你那只能说是查看网页,怎能说是下载呢,总得如存吧



import urllib

webfile = urllib.urlopen("http://www.insenz.com").read()

fp = file('rhf.html', 'a+')

#fp = open('rhf.html', 'a+')

fp.write(webfile)

fp.close()










TOP





















回复 #3 hongfu 的帖子




运行后得到这个





错误

您所请求的网址(URL)无法获取



--------------------------------------------------------------------------------



当尝试进行以下请求时:



GET  HTTP/1.0



Host: www.insenz.com



User-Agent: Python-urllib/1.17









发生了下列的错误:



Invalid Request

无效的请求

Some aspect of the HTTP Request is invalid. Possible problems:

HTTP 请求的某些方面是无效的。可能是下列问题:



Missing or unknown request method

缺少请求方式或未知的请求方式

Missing URL

缺少网址

Missing HTTP Identifier (HTTP/1.0)

缺少 HTTP 标识(HTTP/1.0)

Request is too large

请求命令过长

Content-Length missing for POST or PUT requests

POST 或 PUT 请求缺少内容长度

Illegal character in hostname; underscores are not allowed

主机名称中包含不合法的字符;下划线是不允许的。



本缓存服务器管理员:cacheadmin@discuz.com.







--------------------------------------------------------------------------------



Generated Tue, 10 Jul 2007 09:40:24 GMT by cache.discuz.net (squid/2.5.STABLE14)










TOP























在后边加上index.html试一下







Invalid Request

无效的请求

Some aspect of the HTTP Request is invalid. Possible problems:

HTTP 请求的某些方面是无效的。可能是下列问题:










TOP























恩?? 我就可以呢??










TOP























哦,我没有试 www.insenz.com , 我试的 http://www.pythonid.com










TOP























可能是你访问不了这台服务器,哈哈










TOP























最简单的下载网页的方法只有2句:



from urllib import urlretrieve



urlretrieve('http://www.python.org', 'f:\\python_webpage.html')










TOP


























Sunday, January 18, 2009

python获得并输出文件属性






python获得并输出文件属性
代码:
import os
import time
file = "samples/sample.jpg"
def dump(st):
    mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime = st
    print "- size:", size, "bytes"
    print "- owner:", uid, gid
    print "- created:", time.ctime(ctime)
    print "- last accessed:", time.ctime(atime)
    print "- last modified:", time.ctime(mtime)
    print "- mode:", oct(mode)
    print "- inode/dev:", ino, dev
# get stats for a filename
st = os.stat(file)
print "station", file
dump(st)
print st

# get stats for an open file
fp = open(file)
st = os.fstat(fp.fileno())
print "fstat", file
dump(st)

print st.st_ctime


201865413.8952832



import os
>>> o=os.stat(r'F:\\Xunlei\160103.doc')
>>> t=o.st_ctime
>>> t
1202624180.046875
>>> print type(t)
<type 'float'>
>>> import time
>>> r=time.ctime(t)
>>> r
'Sun Feb 10 14:16:20 2008'
>>> s=time.gmtime(t)
>>> s
(2008, 2, 10, 6, 16, 20, 6, 41, 0)
>>> time.strftime("%a, %d %b %Y %H:%M:%S +0000", s)
'Sun, 10 Feb 2008 06:16:20 +0000'

Sunday, December 28, 2008

我知道的几个GAE blog的源码地址






我知道的几个GAE blog的源码地址
2008年07月17日 星期四 19:00
代码在 http://code.google.com/p/pyweblog/    具体样子参见:http://plog.appspot.com/

代码在 http://code.google.com/p/n23/   具体样子参见:http://n23.appspot.com/blog

代码在 http://code.google.com/p/xian-min/   具体样子参见:http://xian-min.appspot.com/

http://code.google.com/p/tublog/

http://github.com/araddon/potlatchblog/tree/master

http://code.google.com/p/gaeblog/


    代码可以自行使用SVN下载,倒腾几分钟就可以用了。哪个都行,主要是参考学习一下GAE的用法。

    前些时候看了一些源码,后来记住的中国人写的blog源码地址就这几个了。期中,pyweblog是第一个写的,N23同学在上面改了一下衍生了他自己的版本。xian-min的版本出来的比较晚。


Sunday, December 21, 2008

Python&OpenCV






Python&OpenCV





Wikipedia,自由的百科全书




目前OpenCV支持的Python版本为2.4版.所以我们这里使用2.4为范例.
但是如果你用2.5也能做到请帮忙修改一下这个页面,让大家知道2.5也可以,并且说明需要怎么设置和使用,存在什么问题.


目录

[隐藏]





安装Python


Python
一种面向对象、解释性的计算机程序设计语言,也是一种功能强大而完善的通用型语言,已经具有十多年的发展历史,成熟且稳定。这种语言具有非常简捷而清晰的
语法特点,适合完成各种高层任务,几乎可以在所有的操作系统中运行。目前,基于这种语言的相关技术正在飞速的发展,用户数量急剧扩大,相关的资源非常多。


Windows用户


Python的安装,可以直接去 http://www.python.org 下载最新版本2.5.1。

opencv4python2.5下载地址:http://www.interactive-china.net/viewthread.php?tid=235&extra=page%3D1

安装完毕之后,请把opencv4python2.5压缩包解压,然后放到你的Python安装目录的所在地。假如Python安装在
D:\Program Files\Python\,那么将解压后的文件放到 D:\Program
Files\Python\Lib\site-packages\,然后在D:\Program
Files\Python\Lib\site-packages\
里新建一个文档,保存为Opencv.pth,里面的内容写入OpenCV。这样就完成了基本的设置,可以开始在python下调用OpenCV来写东西
了。


Linux用户


Linux用户就好办了,系统默认就有,只是可能版本是2.5的.
用python --version看一下


OpenCV Python的范例


  1.  
  2. #! /usr/bin/env python
  3.  
  4. import sys
  5.  
  6. # import the necessary things for OpenCV
  7. #原先范例的格式是下面的两行,也就是from opencv.cv import*
  8. #这里需要改为import cv 和import highgui,然后就可以了。
  9. #from opencv.cv import *
  10. #from opencv.highgui import *
  11. import cv
  12. import highgui
  13.  
  14. # the codec existing in cvcapp.cpp,
  15. # need to have a better way to specify them in the future
  16. # WARNING: I have see only MPEG1VIDEO working on my computer
  17.  
  18. import ctypes
  19. H263 = 0x33363255
  20. H263I = 0x33363249
  21. MSMPEG4V3 = 0x33564944
  22. MPEG4 = 0x58564944
  23. MSMPEG4V2 = 0x3234504D
  24. MJPEG = 0x47504A4D
  25. MPEG1VIDEO = 0x314D4950
  26. AC3 = 0x2000
  27. MP2 = 0x50
  28. FLV1 = 0x31564C46
  29.  
  30. # so, here is the main part of the program
  31.  
  32. if __name__ == '__main__':
  33.  
  34. # a small welcome
  35. print "OpenCV Python capture video"
  36.  
  37. # first, create the necessary window
  38. highgui.cvNamedWindow ('Camera', highgui.CV_WINDOW_AUTOSIZE)
  39.  
  40. # move the new window to a better place
  41. highgui.cvMoveWindow ('Camera', 10, 10)
  42.  
  43. try:
  44. # try to get the device number from the command line
  45. device = int (sys.argv [1])
  46.  
  47. # got it ! so remove it from the arguments
  48. del sys.argv [1]
  49. except (IndexError, ValueError):
  50. # no device number on the command line, assume we want the 1st device
  51. device = 0
  52.  
  53. if len (sys.argv) == 1:
  54. # no argument on the command line, try to use the camera
  55. capture = highgui.cvCreateCameraCapture (device)
  56. else:
  57. # we have an argument on the command line,
  58. # we can assume this is a file name, so open it
  59. capture = highgui.cvCreateFileCapture (sys.argv [1])
  60.  
  61. # check that capture device is OK
  62. if not capture:
  63. print "Error opening capture device"
  64. sys.exit (1)
  65.  
  66. # capture the 1st frame to get some propertie on it
  67. frame = highgui.cvQueryFrame (capture)
  68.  
  69. # get size of the frame
  70. frame_size = cv.cvGetSize (frame)
  71.  
  72. # get the frame rate of the capture device
  73. fps = highgui.cvGetCaptureProperty (capture, highgui.CV_CAP_PROP_FPS)
  74. if fps == 0:
  75. # no fps getted, so set it to 30 by default
  76. fps = 30
  77.  
  78. # create the writer
  79. writer = highgui.cvCreateVideoWriter ("captured.mpg", MPEG1VIDEO,
  80. fps, frame_size, True)
  81.  
  82. # check the writer is OK
  83. if not writer:
  84. print "Error opening writer"
  85. sys.exit (1)
  86.  
  87. while 1:
  88. # do forever
  89.  
  90. # 1. capture the current image
  91. frame = highgui.cvQueryFrame (capture)
  92. if frame is None:
  93. # no image captured... end the processing
  94. break
  95.  
  96. # write the frame to the output file
  97. highgui.cvWriteFrame (writer, frame)
  98.  
  99. # display the frames to have a visual output
  100. highgui.cvShowImage ('Camera', frame)
  101.  
  102. # handle events
  103. k = highgui.cvWaitKey (5)
  104.  
  105. if k % 0x100 == 27:
  106. # user has press the ESC key, so exit
  107. break
  108.  
  109. # end working with the writer
  110. # not working at this time... Need to implement some typemaps...
  111. # but exiting without calling it is OK in this simple application
  112. #highgui.cvReleaseVideoWriter (writer)
  113.  

python各种实用代码片段 zz

python各种实用代码片段 zz
发信站: 水木社区 (Tue Oct  9 10:45:59 2007), 转信

zzfrom: http://www.wujianrong.com/archives/2007/07/python_12.html

1. 各种实用代码片段
1.1. 正则表达式使用
###########################################################
特殊字符:
###########################################################
   "."      匹配除 "\n" 之外的任何单个字符。要匹配包括 '\n' 在内的任何字符,请使用象 '[.\n]' 的模式。
   "^"      匹配输入字符串的开始位置。
   "___FCKpd___0quot;      匹配输入字符串的结束位置。
   "*"      匹配前面的子表达式零次或多次。例如,zo* 能匹配 "z" 以及"zoo"。 * 等价于{0,}。 Greedy means 贪婪的
   "+"      匹配前面的子表达式一次或多次。例如,'zo+' 能匹配 "zo" 以及 "zoo",但不能匹配 "z"。+ 等价于 {1,}。
   "?"      匹配前面的子表达式零次或一次(贪婪的)
   *?,+?,?? 前面三个特殊字符的非贪婪版本
   {m,n}    最少匹配 m 次且最多匹配 n 次(m 和 n 均为非负整数,其中m <= n。)
   {m,n}?   上面表达式的非贪婪版本.
   "\\"      Either escapes special characters or signals a special sequence.
   []       表示一个字符集合,匹配所包含的任意一个字符
            第一个字符是 "^" 代表这是一个补集
   "|"      A|B, 匹配 A 或 B中的任一个
   (...)    Matches the RE inside the parentheses(圆括号).(匹配pattern 并获取这一匹配)
            The contents can be retrieved(找回) or matched later in the string.
   (?iLmsux) 设置 I, L, M, S, U, or X 标记 (见下面).
   (?:...)  圆括号的非成组版本.
   (?P<name>...) 被组(group)匹配的子串,可以通过名字访问
   (?P=name) 匹配被组名先前匹配的文本(Matches the text matched earlier by the
group named name.)
   (?#...)  注释;被忽略.
   (?=...)  Matches if ... matches next, but doesn't consume the
string(但是并不消灭这个字串.)
   (?!...)  Matches if ... doesn't match next.

The special sequences consist of "\\" and a character from the list
below.  If the ordinary character is not on the list, then the
resulting RE will match the second character.
   \number  Matches the contents of the group of the same number.
   \A       Matches only at the start of the string.
   \Z       Matches only at the end of the string.
   \b       Matches the empty string, but only at the start or end of a word
                                       匹配一个空串但只在一个单词的开始或者结束的地方.匹配单词的边界
   \B       匹配一个空串, 但不是在在一个单词的开始或者结束的地方.(匹配非单词边界)
   \d       匹配一个数字字符。等价于 [0-9]。
   \D       匹配一个非数字字符。等价于 [^0-9]。
   \s       匹配任何空白字符,包括空格、制表符、换页符等等。等价于[ \f\n\r\t\v]。
   \S       匹配任何非空白字符。等价于 [^ \f\n\r\t\v]。
   \w       匹配包括下划线的任何单词字符。等价于'[A-Za-z0-9_]'.
            With LOCALE, it will match the set [0-9_] plus characters defined
            as letters for the current locale.
   \W       匹配\w的补集(匹配任何非单词字符。等价于 '[^A-Za-z0-9_]'。)
   \\       匹配一个"\"(反斜杠)

##########################################################
共有如下方法可以使用:
##########################################################
   match    从一个字串的开始匹配一个正则表达式
   search   搜索匹配正则表达式的一个字串
   sub      替换在一个字串中发现的匹配模式的字串
   subn     同sub,但是返回替换的个数
   split    用出现的模式分割一个字串
   findall  Find all occurrences of a pattern in a string.
   compile  把一个模式编译为一个RegexObject对像.
   purge                       清除正则表达式缓存
   escape   Backslash(反斜杠)all non-alphanumerics in a string.

Some of the functions in this module takes flags as optional parameters:
   I  IGNORECASE  Perform case-insensitive matching.(执行大小写敏感的匹配)
   L  LOCALE      Make \w, \W, \b, \B, dependent on the current locale.
   M  MULTILINE   "^" matches the beginning of lines as well as the string.
                  "___FCKpd___0quot; matches the end of lines as well as the string.
   S  DOTALL      "." matches any character at all, including the newline(换行符).
   X  VERBOSE     Ignore whitespace and comments for nicer looking RE's.
   U  UNICODE     Make \w, \W, \b, \B, dependent on the Unicode locale.

This module also defines an exception 'error'.

compile(pattern, flags=0)
返回一个模式对像
Compile a regular expression pattern, returning a pattern object.

escape(pattern)
Escape all non-alphanumeric characters in pattern.

findall(pattern, string)
如果出现一个或多个匹配,返回所有组的列表;这个列表将是元组的列表。
空匹配也在返回值中
Return a list of all non-overlapping(不相重叠的) matches in the string.
If one or more groups are present in the pattern, return a
list of groups; this will be a list of tuples if the pattern
has more than one group.
Empty matches are included in the result.

finditer(pattern, string)
返回一个指示器(iterator);每匹配一次,指示器返回一个匹配对像。
空匹配也在返回值中
Return an iterator over all non-overlapping matches in the
string.  For each match, the iterator returns a match object.
Empty matches are included in the result.

match(pattern, string, flags=0)
返回一个匹配的对像,如果没有匹配的,返回一个None
Try to apply the pattern at the start of the string, returning
a match object, or None if no match was found.

purge()
Clear the regular expression cache

search(pattern, string, flags=0)
返回一个匹配的对像,如果没有匹配的,返回一个None
Scan through string looking for a match to the pattern, returning
a match object, or None if no match was found.

split(pattern, string, maxsplit=0)
返回一个包含结果字串的列表
Split the source string by the occurrences of the pattern,
returning a list containing the resulting substrings.

sub(pattern, repl, string, count=0)
返回一个字串,最左边被不重叠的用"repl"替换了。
Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl

subn(pattern, repl, string, count=0)
返回一个包含(new_string, number)的2元组;number是替换的次数
Return a 2-tuple containing (new_string, number).
new_string is the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in the source
string by the replacement repl.  number is the number of
substitutions that were made.

template(pattern, flags=0)
返回一个模式对像
Compile a template pattern, returning a pattern object

_______________________________________________
python-chinese list
python-chinese@lists.python.cn
http://python.cn/mailman/listinfo/python-chinese

{PyRe}
1.2. 自动检查md5sums
"       From: steve <lau.siyuan@gmail.com>
Toggle line numbers Toggle line numbers Toggle line numbers
   1 #! /usr/local/bin/python
   2
   3 import commands
   4 file = raw_input("Enter the filename: ")
   5 sum = raw_input("Enter the md5sum: ")
   6 md = "md5sum " + file
   7 print md
   8 check = str(commands.getoutput(md))
   9 checksum = sum + "  " + file
  10 #print checksum
  11 print check
  12 if check == checksum: print "Sums OK"
  13 else: print "Sums are not the same!"
1.3. 提取网页中的超链接
Toggle line numbers Toggle line numbers Toggle line numbers
   1 r='<a(?:(?:\\s*.*?\\s)|(?:\\s+))href=(?P<url>\S*?)(?:(?:\\s.*>)|(?:>)).*?</a>'
   2 compile(r).findall(a)
"       这个是hoxide和天成讨论出来的方法,用来提取网页中的超链接.
1.4. 解决在 Python 中登录网站的问题
刚刚看了xyb的代码,有点启发。
写了一小段试了以下,可以登录了。呵呵。
import httplib
import urllib
user=?
pwd=?
params=urllib.urlencode({"Loginname":user,"Loginpass":pwd,"firstlogin":1,"option":"登入论坛"})
headers={"Accept":"text/html","User-Agent":"IE","Content-Type":"application/x-www-form-urlencoded"}
website="www.linuxforum.net"
path="/forum/start_page.php"
conn=httplib.HTTPConnection(website)
conn.request("POST",path,params,headers)
r=conn.getresponse()
print r.status,r.reason
data=r.read()
print data
conn.close()

不知从form submit数据和直接提交request有些什么区别?


"       中国Linux论坛
"       由xyb总结:PythonClientCookie
1.5. 浮点数的输出格式
>>> a=6200-6199.997841
>>> a
0.0021589999996649567
>>> print "%f"%a
0.002159
>>> import fpformat
>>> fpformat.fix(a, 6)
'0.002159'
>>> print fpformat.fix(a, 6)
0.002159
>>> print "%.6f"%a
0.002159
>>> print "%.7f"%a
0.0021590
>>> print "%.10f"%a
0.0021590000
>>> print "%.5f"%a
0.00216

1.6. 怎么下载网络上的一张图片到本地
>知道了一张图片的URL >比如http://www.yahoo.com/images/logo.gif >想将它下载到本地保存应该怎么实现?
Toggle line numbers Toggle line numbers Toggle line numbers
   1 urllib.urlretrieve(url, filename)
---Limodou
1.7. 使用locale判断本地语言及编码
from::limodou的学习记录
在支持unicode软件中,经常需要在不同的编码与unicode之间进行转换。
那么对于一个本地文件的处理,首先要将其内容读出来转换成unicode编码,在软件中处理完毕后,再保存为原来的编码。
如果我们不知道文件的确切编码方式,可以使用默认的编码方式。那么我们可以使用locale模块来判断默认编码方式。
>>>import locale
>>>print locale.getdefaultlocale()
('zh_CN', 'cp936')

可以看出,我的机器上默认语言是简体中文,编码是GBK。
1.8. __new__的使用
from: 中国Linux论坛 -rings
new
new
是python里object的方法。如果你要重载new,那么你需要继承object。 new是类方法。他不带self参数。
new和init是不一样的。init带 self参数。所以他是在对象已经被构造好了以后被调用的。而如果你要在对象构造的时候
做一些事情,那么就需要使用new。new的返回值必须是对象的实例。 new一般在 一些模式里非常有用。我们看一个例子。
这个例子是《thinking in python》里的一个Singleton例子
class OnlyOne(object):
    class __OnlyOne:
        def __init__(self):
            self.val = None
        def __str__(self):
            return ′self′ + self.val
            
        instance = None
        def __new__(cls): # __new__ always a classmethod
            if not OnlyOne.instance:
            OnlyOne.instance = OnlyOne.__OnlyOne()
            return OnlyOne.instance
        def __getattr__(self, name):
            return getattr(self.instance, name)
        def __setattr__(self, name):
            return setattr(self.instance, name)

x = OnlyOne()
x.val = 'sausage'
print x
y = OnlyOne()
y.val = 'eggs'
print y
z = OnlyOne()
z.val = 'spam'
print z
print x
print y

我们可以看到OnlyOne从object继承而来。
如果你不继承object,那么你的 new就不会在构造的时候来调用。
当x = OnlyOne()的时候,其实就是调用new(OnlyOne), 每次实例化OnlyOne 的时候都会调用。
因为他是类方法。
所以这段代码就是利用这个特性来实现Singleton的。
因为不管构造多少对象,都要调用new.
那么在OnlyOne里保持一个类的属性, instance.
他代表嵌套的_OnlyOne的实例。
所以,对于他,我们只构造一次。
"       以后每次构造的时候都是 直接返回这个实例的。
所以,在这里, x,y,z 都是同一个实例。
这个方法和典型的用C++ 来实现 Singleton的道理是一样的。
1.9. traceback 的处理
from::Limodou的学习记录
trackback在 Python 中非常有用,它可以显示出现异常(Exception)时代码执行栈的情况。 但当我们捕捉异常,一般是自已的出错处理,因此代码执行栈的信息就看不到了,如果还想显 示的话,就要用到traceback模块了。
这里只是简单的对traceback模块的介绍,不是一个完整的说明,而且只是满足我个人的要求, 更详细的还是要看文档。
打印完整的traceback
让我们先看一个traceback的显示:
>>> 1/0

Traceback (most recent call last):
  File "", line 1, in -toplevel-
    1/0
ZeroDivisionError: integer division or modulo by zero

可以看出 Python 缺省显示的traceback有一个头:第一行,出错详细位置:第二、三行, 异常信息:第四行。也就是说分为三部分,而在traceback可以分别对这三部分进行处理。 不过我更关心完整的显示。
在traceback中提供了print_exc([limit[, file]])函数可以打印出与上面一样的效果。 limit参数是限定代码执行栈的条数,file参数可以将traceback信息输出到文件对象中。缺省的话是输出到错误输出中。举例:
>>> try:
    1/0
except:
    traceback.print_exc()
 
Traceback (most recent call last):
  File "", line 2, in ?
ZeroDivisionError: integer division or modulo by zero

当出现异常sys.exc_info()函数会返回与异常相关的信息。如:
>>> try:
    1/0
except:
    sys.exc_info()

(<class exceptions.ZeroDivisionError at 0x00BF4CC0>,
<exceptions.ZeroDivisionError instance at 0x00E29DC8>,
<traceback object at 0x00E29DF0>)

sys.exc_info()返回一个tuple,异常类,异常实例,和traceback。
print_exc()是直接输出了,如果我们想得到它的内容,如何做?使用 format_exception(type, value, tb [,limit]),type, value, tb分别对应 sys.exc_info()对应的三个值。如:
>>> try:
    1/0
except:
    type, value, tb = sys.exc_info()
 print traceback.format_exception(type, value, tb)

['Traceback (most recent call last):\n', '  File "", line 2, in ?\n',
'ZeroDivisionError: integer division or modulo by zero\n']

这样,我们知道了format_exception返回一个字符串列表,这样我们就可以将其应用到我们的程序中了。
1.10. os.walk()的用法, 修改cvsroot
"       重装系统, windows盘符大乱, 原来是'e:\cvsroot'现在变为'g:\cvsroot', 众多由cvs管理的目录无法正常工作了. python脚本出动:
Toggle line numbers Toggle line numbers Toggle line numbers
   1 import os
   2 from os.path import join, getsize
   3 import sys
   4
   5 print sys.argv[1]
   6 for root, dirs, files in os.walk(sys.argv[1]):
   7     if 'CVS' in dirs:
   8         fn = join(root+'\CVS', 'ROOT')
   9         print root+' :', fn
  10         #dirs.remove('CVS')  # don't visit CVS directories
  11         f = open(fn,'r')
  12         r = f.read()
  13         print r
  14         f.close()
  15         if r.startswith('e:\cvsroot'):
  16             open(fn, 'w').write('g:\cvsroot')
  17             f = open(fn,'r')
  18             r = f.read()
  19             print r
  20             f.close()
2. Python多进程处理之参考大全
* PyCourse --from
http://blog.huangdong.com (即将成为历史的HD的个人blog,大家默哀)  
3. 将你的Python脚本转换为Windows exe程序
from:: http://blog.huangdong.com (即将成为历史的HD的个人blog,大家默哀)  
将Python的脚本变为一个可以执行的Windows exe程序可能的好处会说出很多,我最喜欢的则是它会让你写的程序更像是一个"程序"罢。但是,凡事有利就有弊,这样必然会让python的一些好处没有了。
你可以从这里找到py2exe的相关信息,可以在这里下载到py2exe-0.4.2.win32-py2.3.exe安装包。 但是它的使用也还是比较麻烦的,需要你自己手工的写一个小的脚本,就像这样:
Toggle line numbers Toggle line numbers Toggle line numbers
   1 # setup.py
   2 from distutils.core import setup
   3 import py2exe
   4
   5 setup(name="myscript",
   6 scripts=["myscript.py"],
   7 )
再通过python的执行:
python setup.py py2exe

来使用。更多的信息上它的网站看罢。
4. 使用 WinAPI 的例子
"       /PyWinApi -- 简单范例
5. 在函数中确定其调用者 !
"       AlbertLee
"       /PyCallParent
6. Python哲学--内省的威力
"       AlbertLee
"       Xie Yanbo 引发
"        
"       Remember, Python comes with batteries included!
"       PyBatteriesIncluded -- 使用内省的功能,获得丰富的信息
7. 在正则表达式中嵌入注释时的陷阱
如下代码所示:
s = 'create table testtable'
>>> p =  r"""
^create\ table   # create table
\s*                 # whitespace
([a-zA-Z]*)      # table name
$                   # end
"""
>>> re.compile(p, re.VERBOSE).match(s).groups()
('testtable',)
>>>

如果在create和table之间没有那个转义的空格,即\ ,在re.VERBOSE 的时候,就会将那个空格忽略掉,因此变成是匹配createtable了,这样 他就会匹配不到了
8. python写的数字转中文的程序
"       源于qq上Jaina(16009966)的提问. 花了一个晚上实现了一下, 基本想法是4位为一个断, 用conv4转换, 然后再用conv组合之. 程序在Windows2003, python2.4下调试通过. 注意编码问题.
Toggle line numbers Toggle line numbers Toggle line numbers
   1 # coding:utf-8
   2
   3 UUNIT=[u'', u'十' , u'百' , u'千']
   4 BUINT = [u'', u'万', u'亿', u'万亿' , u'亿亿']
   5 NUM=[u'零',u'一',u'二', u'三', u'四', u'五' , u'六', u'七', u'八', u'九']
   6
   7 def conv4(num, flag=False):
   8    ret = u''
   9    s = str(num)
  10    l = len(s)
  11    assert(len(s) <= 4)
  12    if flag and len(s)<4:
  13       ret = ret + NUM[0]
  14    for i in xrange(l):
  15       if s[i] != '0':
  16          ret = ret + NUM[int(s[i])]+UUNIT[l-i-1]
  17       elif s[i-1] != '0':
  18          ret = ret + NUM[0]
  19    return ret
  20
  21 def conv(num):
  22    ss = str(num)
  23    l = len(ss)
  24    j = l / 4
  25    jj = l % 4
  26    lss = [ss[0:jj] for i in [1] if ss[0:jj]] \
       + [ss[i*4+jj:(i+1)*4+jj] for i in xrange(j) if ss[i*4+jj:(i+1)*4+jj] ]
  27    print lss
  28    ul = len(lss)
  29    ret = u''
  30    zflag = False
  31    for i in xrange(ul):
  32       bu = BUINT[ul-i-1]
  33       tret = conv4(int(lss[i]), flag = i)
  34       if tret[-1:] == NUM[0]:
  35          tret = tret[:-1]
  36       if tret:
  37          print zflag , (tret+bu).encode('mbcs')
  38          if zflag and tret[0] != NUM[0] :
  39             ret = ret + NUM[0] +tret+bu
  40          else:
  41             ret = ret + tret+bu
  42          zflag = False
  43       else:
  44          zflag = True
  45    return ret
  46
  47 if __name__ == '__main__':
  48    #print conv(11111)
  49    print conv(103056).encode('mbcs')
  50    print conv(101000).encode('mbcs')
  51    print conv(1200999100000000010).encode('mbcs')

(转载)