26 Mar 2009

Python Tips之 - 操作Windows剪贴板

Python学习笔记: 操作Windows剪贴板

This article is mainly about using Windows Clipboard

22/11/2009 updata: 另外一篇关于剪贴板的帖子,看这里.

必须安装PyWin32,可惜,我的PyWin在安装ActivePython失败之后,一直弹出vs Debugging,出错不能运行.谁知道怎么解决吗?无奈,只好继续IDLE了.习惯就好.(PyWin32下载地址: http://sourceforge.net/projects/pywin32/)

In order to use this code, you have to install PyWin32 from the source forge:
http://sourceforge.net/projects/pywin32/
Unfortunately, it didn't work for me. Maybe because I have been faild to install ActivePython.
The VS Debugging dialog would appear if I tried to run it. Can anybody help? Please leave a comment.

安装好之后,就可以操作剪贴板了,代码如下:
You can use clipboard as soon as you install the pywin32 modules as following:



>>> import win32clipboard, win32con
>>> txt = 'Some text'
>>> win32clipboard.OpenClipboard()
>>> win32clipboard.EmptyClipboard()
>>> win32clipboard.SetClipboardData(win32con.CF_TEXT,txt)
>>> print win32clipboard.GetClipboardData()
Some text
>>> win32clipboard.CloseClipboard()
>>> 

24 Mar 2009

Python学习笔记 - 4:基本运算符与原地运算优化

本文主要有: 基本运算符及优化使用

This article is mainly about Basic Operators and Optimization Usage

Python的运算符跟其他语言几乎完全一样,但是也有几个特殊的需要单独说明一下:

Python has lots of common operators as other programming languages, like c/c++ and java. However, there are some special ones which need to pay attention to:
/               除法,如果除数,被除数全为整形,返回整形商数,否则返回浮点数
%             取余函数,得到除法的余数
**            乘幂函数, x ** y <=> pow(x, y)
//              (地板除,我不知道名字怎么来的),可以返回商的整数部分,即使除数,被除数有浮点数.
divmod     同时得到商数和余数,并返回一个tuple(这非常方便)

/               division, if both divisor and dividend are integer, return integer; otherwise, return float point.
%             remainder function, got the remainderof division
**            power function, x ** y equals to pow(x, y)
//             floor division, return integer part of quotient, even there is float point number within divisor and dividend.
divmod    return integer quotient and remainder as a tuple. (It's quite convenient for developer)


测试如下:

Following are some examples:

Python学习笔记 - 3:逻辑表达式与三目运算

本文主要有: 逻辑表达式

This article is mainly about Logical Expression

Python的逻辑运算主要有 and/or/XOR(与,或,异或), 全部都是二值运算符,这跟其他语言并无区别.

Python has the same logic operators as other languages, such as AND, OR, XOR. They are all Binary Operators.

求值规则为:

Evaluation rules are:



1    非零数字,非空list, tuple, dict, string都返回TRUE
2    零, None, 空list, tuple, dict, string都返回FALSE


1    Non-zero number, non-empty list, tuple, dict, string return TRUE
2    Zero, None,  empty list, tuple, dict, string return FALSE

运算规则为:

Algorithm are:

1    a and b    如果a为TRUE,返回b;否则返回a
2    a or b      如果a为TRUE,返回a;否则返回b
3    not a       如果a为TRUE,返回FALSE,否则返回TRUE
4    从左到右运算, 有短路行为,也就是说只有在需要时才进一步计算.


1    a and b    return b if a is TRUE; otherwise return a
2    a or b      return a if a is TRUE; otherwise return b
3    not a       return TRUE is a is FALSE; otherwise return TRUE
4    from left to right, short circuit behaviour



具体实例:

Examples:

*** Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32. ***
>>> a = 'a'; b = []; c = 0
>>> bool(a)
True
>>> bool(b)
False
>>> bool(c)
False
>>> bool(not c)
True


Python中没有三目运算符 a?b:c,但是可以用下面的方法来实现:

Python has no ternary operator like a?b:c, but it's also possible to get the same results by:

if a: return b
else: return c


其实更简单的办法是逻辑运算符连用:

Actually, there is another simple method:

a and b or c


但是要注意: 如果b为FALSE,则不能用这个表达,
原因见上面关于Python计算and or的求值及运算规则.

NOTE: if b is FALSE, it can not be applied any more.

测试如下:

Test:

>>> if a=='a': print b
... else: print c
... 
[]
>>> print a=='a' and b or c
0
>>> b.append('b')
>>> b
['b']
>>> bool(b)
True
>>> print a=='a' and b or c
['b']


来分析下上面的三目运算, a and b or c:

Following is the analysis:

a and b or c <=> (a and b) or c
1        计算a and b, 如果a为true,返回b,
1.1            如果b为TRUE,整个(a and b)为TRUE,否则为FLASE
2        计算(a and b) or c
2.1            如果a为TRUE,(a and b)返回b,继续计算b的逻辑值
如果b的值为TRUE, (..)返回TRUE,就不会继续计算c了,返回值就是b
如果b的值为FALSE,(..)返回FALSE; (..) or c返回值就是c
2.2            如果a为FALSE,(a and b)返回a的值,也就是FALSE,短路规则不计算b
(..) or c直接返回c


a and b or c <=> (a and b) or c
1        compute a and b,if a is true, return b,
1.1            if b is TRUE, whole (a and b) is TRUE, otherwise FLASE
2        compute (a and b) or c
2.1            if a is TRUE, whole (a and b) returns b, go on to compute b
if b is TRUE, (..) returns TRUE, it is not necessary to compute c. return b
if b is FALSE,(..) returnsFALSE; (..) or c returns c
2.2            if a is FALSE,(a and b) returns a, namely FALSE. It is not necessary to compute b
(..) or c returns c


通过分析可以看出,利用a and b or c 替代三目运算符有一个需要注意的地方,
就是b的逻辑值,必须为TRUE.如果b本身是零, None, 空list, tuple, dict或者空string,
还是必须继续使用if... else... 结构.

It's easy to find that: if you want to use a AND b OR c. as ternary operator, you must make sure that b is TRUE. If b is one of Zero, None, empty list, empty tuple, empty dict or empty string, you have to use
if .. else .. structure.

22 Mar 2009

Python GUI学习之 - wxPython界面编程: QR Code

2009/11/18:
判断平台可以直接sys.platform

4月20日更新:
判断平台可以直接利用函数os.environ.get('OS')或者os.environ['OS']会返回操作系统名称.


4月1日更新:
使用os.sep,可以表示文件路径分隔符,Python会自动根据平台选择/(linux,unix)或者\\(windows)




这是为了学习wxPython而编写的一个QR Code Generator程序,
可以把输入的信息保存成图片(png,jpg,gif)格式。

QR Code目前已经有很多应用,下次买pepsi的时候看看上面有个黑色的方块就是了,没有注意coca是不是也有。
做成的大概样子就是左边的样子了:

代码如下:(很不幸,PyQrcodec模块在windows下工作不了,看了作者主页的解决方法,只在ubuntu下解决了)


-------------------------------------------
#!/usr/bin/env python
#
# QrGenerate.py
#
# Copyright 2009 daniel
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

import os
import wx
import PyQrcodec

ID_New = 101
ID_Encode = 102
ID_Decode = 103
ID_Exit = 104
ID_About = 201
ID_Help = 202

class QrGenerate(wx.App):

    def OnInit(self):
        frame = BasicFrame(None, -1, "QrGenerator - Generate QR Code for you")
        
        #~ frame.Show(True)
        frame.CentreOnScreen()
        frame.Show(True)
        
        #~ one way to bind menu items and event
        frame.Connect(ID_New, -1,
                      wx.wxEVT_COMMAND_MENU_SELECTED, frame.OnNew)
        frame.Connect(ID_Encode, -1,
                      wx.wxEVT_COMMAND_MENU_SELECTED, frame.OnEncode)
        frame.Connect(ID_Decode, -1,
                      wx.wxEVT_COMMAND_MENU_SELECTED, frame.OnDecode)
        frame.Connect(ID_Exit, -1,
                      wx.wxEVT_COMMAND_MENU_SELECTED, frame.OnExit)
        frame.Connect(ID_Help, -1,
                      wx.wxEVT_COMMAND_MENU_SELECTED, frame.OnHelp)
        frame.Connect(ID_About, -1,
                      wx.wxEVT_COMMAND_MENU_SELECTED, frame.OnAbout)
        
        self.SetTopWindow(frame)
        return True;
##---------------------------------------

class BasicFrame(wx.Frame):

    def __init__(self, parent, ID, title):
        wx.Frame.__init__(self, parent, ID, title,
        wx.DefaultPosition, wx.Size(450,300))
        self.CreateStatusBar()
        self.SetStatusText("QrGenerator - Generate QR Code for you")

        #~ menus start here
        menu1 = wx.Menu()
        menu1.Append(ID_New,
                     "&New", "Create new QR Code picture")
        menu1.Append(ID_Encode,
                     "E&ncode", "Generate the QR picture with current string")
        menu1.Append(ID_Decode,
                     "&Decode", "Decode the information from a picture file")
        menu1.AppendSeparator()
        menu1.Append(ID_Exit,
                     "&Exit", "Terminate program")

        #~ add it to the menubar
        menuBar = wx.MenuBar()
        menuBar.Append(menu1, "&File")

        #~ add another menu
        menu2 = wx.Menu()
        menu2.Append(ID_Help,
                     "&Help", "See more about the usage...")
        menu2.AppendSeparator()
        menu2.Append(ID_About,
                     "&About", "More information about this program")
        menuBar.Append(menu2, "&Help")

        #~ set menubar
        self.SetMenuBar(menuBar)
        #~ another way to bind menu items and event
        #~ wx.EVT_MENU(self, ID_ABOUT, self.OnAbout)
        #~ ...

        #~ set textbox
        self.TxtInfo = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE)
        #~ set buttons
        self.buttons = []
        self.buttons.append(wx.Button(self, id=1, label="&Clear"))
        self.Bind(wx.EVT_BUTTON, self.OnClear,self.buttons[len(self.buttons)-1])
        self.buttons[len(self.buttons)-1].SetToolTip(wx.ToolTip('Clear the input aera'))
        
        self.buttons.append(wx.Button(self, id=2, label="&Encode"))
        self.Bind(wx.EVT_BUTTON, self.OnEncode,self.buttons[len(self.buttons)-1])
        self.buttons[len(self.buttons)-1].SetToolTip(wx.ToolTip('Generate the QR picture with current string'))
        
        self.buttons.append(wx.Button(self, id=3, label="&Decode"))
        self.Bind(wx.EVT_BUTTON, self.OnDecode,self.buttons[len(self.buttons)-1])
        self.buttons[len(self.buttons)-1].SetToolTip(wx.ToolTip('Decode the information from a picture file'))
        
        self.buttons.append(wx.Button(self, id=4, label="&Exit"))
        self.Bind(wx.EVT_BUTTON, self.OnExit,self.buttons[len(self.buttons)-1])
        self.buttons[len(self.buttons)-1].SetToolTip(wx.ToolTip('Terminate program'))
        
        #~ set sizer
        self.sizer2 = wx.BoxSizer(wx.HORIZONTAL)
        for i in self.buttons:
            self.sizer2.Add(i,1,wx.EXPAND)
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.TxtInfo,1,wx.EXPAND)
        self.sizer.Add(self.sizer2,0,wx.EXPAND)
        #~ Layout sizers
        self.SetSizer(self.sizer)
        self.SetAutoLayout(1)
        #~ self.sizer.Fit(self)

    def OnNew(self, event):
        if len(self.TxtInfo.GetValue())!=0:
            dlg = wx.MessageDialog(self, """The input aera is not empty,\nare you sure?""",
                                   'QrGenerator',wx.YES_NO | wx.ICON_QUESTION)
            if dlg.ShowModal()==wx.ID_YES: #choose OK
                self.TxtInfo.Clear()
        else:
            self.TxtInfo.Clear()

    def OnClear(self, event):
        self.TxtInfo.Clear()

    def OnEncode(self, event):
        if len(self.TxtInfo.GetValue())!=0:
            dlg = wx.FileDialog(self,'Please specify the file name:',
                                '','','*.jpg;*.gif;*.png', wx.SAVE)
            if dlg.ShowModal() == wx.ID_OK:
                #~ default format png, you can choose from png or jpg or gif
                self.filename = ('.' in dlg.GetFilename()) \
                                and dlg.GetFilename() or dlg.GetFilename()+'.png'
                self.dirname = (dlg.GetDirectory()[len(dlg.GetDirectory())-1]=='/') \
                               and dlg.GetDirectory() or dlg.GetDirectory()+'/'
                size, image = PyQrcodec.encode(self.TxtInfo.GetValue())
                image.save(self.dirname+'/'+self.filename)
                #~ print '%s, %s' % (self.TxtInfo.GetValue(), self.dirname+'/'+self.filename)
                self.SetStatusText("Image has been saved")

    def OnDecode(self, event):
        dlg = wx.FileDialog(self, 'Please specify the file name:',
                            '','','*.jpg;*.gif;*png', wx.OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            if len(dlg.GetFilename())!=0:
                self.filename = dlg.GetFilename()
                self.dirname = (dlg.GetDirectory()[len(dlg.GetDirectory())-1]=='/') \
                               and dlg.GetDirectory() or dlg.GetDirectory()+'/'
                print self.dirname+self.filename
                #~ choose file
                status, string = PyQrcodec.decode(self.dirname+self.filename)
                if status:
                    self.TxtInfo.SetValue(string)
##                    dlg = wx.MessageDialog(self, string,
##                                           "QR Code Information", wx.OK | wx.ICON_INFORMATION)
##                    dlg.ShowModal()
##                    dlg.Destroy()
                    self.SetStatusText("Information has been decoded")
                else:
                    dlg = wx.MessageDialog(self, "There's an ERROR happened!",
                                           "QR Code Information", wx.OK | wx.ICON_ERROR)
                    dlg.ShowModal()
                    dlg.Destroy()

    def OnExit(self, event):
        self.Close(True)

    def OnHelp(self, event):
        dlg = wx.MessageDialog(self, "If you want to know more about QR Code, \
Please visit: \nhttp://en.wikipedia.org/wiki/QR_Code","QrGenerator - Help", wx.OK | wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()

    def OnAbout(self, event):
        dlg = wx.MessageDialog(self, "This is a simple programme for generating QR code as a picture.\nFor more information \
about QR code, please visit wetsite: \n\nhttp://en.wikipedia.org/wiki/QR_Code",
        "About QrGenerator", wx.OK | wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()


#~ main loop
app = QrGenerate(0)
app.MainLoop()

终于可以让blog贴代码

google好歹也是coding出身的大公司啊,收购了blogspot好歹也下点儿功夫啊,
一个blog不让贴代码,真是郁闷.经过痛苦的googling,搞定!
方法如下:(把所有全角字符改成半角,对应的css和js文件去这里下载)


1.在 自定义-布局-修改模板HTML 中,<head>和</head>之间加入:
<link href="your css" type="text/css" rel="stylesheet" />

<script type="text/javascript" src="your js"></script>


2,在把<body>改成
<body onload="prettyPrint()">


3.修在pre标签到你喜欢的样式,比如:
pre {
margin: 5px 20px;
border: 1px dashed #666;
padding: 5px;
background: #f8f8f8;
white-space: pre-wrap;       /* css-3 */
white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
white-space: -pre-wrap;      /* Opera 4-6 */
white-space: -o-pre-wrap;    /* Opera 7 */
word-wrap: break-word;       /* Internet Explorer 5.5+ */
}


4.现在可以在你的帖子里使用代码高亮了!在"修改Html"标签下:
<pre class="prettyprint">
print "Hello world!"
</pre>


参考:
http://google-code-prettify.googlecode.com/svn/trunk/README.html

21 Mar 2009

Python学习笔记 - 2:特殊字符和标识符

本文主要有: 特殊字符和标识符
--------------------------------------
特殊字符


\

续行符


\\

反斜杠



单引号


\"

双引号


\a

系统响铃


\b

退格


\e

escape


\0

NULL(空值)


\n

换行,等价于\x0a和\cJ


\v

垂直制表符,等价于\x0b和\cK


\t

水平制表符,等价于\x09和\cI


\r

回车,等价于\x0d和\cM


\f

换页,等价于\x0c和\cL


\OOO

八进制值(000-377)


\xhh

十六进制(x00-xff)


\un

Unicode字符,n是4个十六进制数字表示的Unicode字符


标识符

标识符可以用来识别变量,函数,类,模块以及对象. Python的标识符必须以非数字开始,可以使用字母,数字以及下划线. Python的标识符是大小写敏感的.

注意:
1)以下划线开始或者结束的标识符通常具有特殊意义.例如一个以下划线开始的函数_foo将不能用from module import * 导入.

2)前后均有2个下划线的标识符,例如__init__,被特殊方法保留.

3)前边有2个下划线的标识符,例如__fAttr用来实现类私有属性.