终于用上了unladen-swallow

Tags: Python

Shell:~ >: python
Python 2.6.1 (r261:900M, Nov 18 2009, 17:55:22)
[GCC 4.3.2] on linux2
[Unladen Swallow 2009Q4]
Type "help", "copyright", "credits" or "license" for more information.
>>>

 

由于OpenSolaris太慢了,换成Debian,终于可以用unladen-swallow.

No Comments 2009-11-19 09:18:59 by No.0023

bpython Screenshots

Tags: Python

No Comments 2009-11-11 22:34:04 by No.0023

python exec

Tags: Python

In Python 2, exec is actually implemented as a special language statement,
whereas Python 3 implements it as a standard library function.

在python2是语句,在python3已经是标准的库函数了。

1 Comment 2009-10-27 15:59:53 by No.0023

Python sendmail

Tags: Python

http://code.google.com/p/mylibs/source/browse/lib/Python/MyPyLib/smtp_client.py :

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

# Copyright 2009 N23 <No.0023@gmail.com>
# All rights reserved.

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

__all__ = ['get_smtp_client', 'sendmail']

import os, sys
from ConfigParser import ConfigParser
from ConfigParser import NoOptionError

from smtplib import SMTP
from smtplib import SMTPAuthenticationError
from email import Encoders
from email.base64MIME import encode as encode_base64
from email.MIMEBase import MIMEBase
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

def get_smtp_client(stor):
    host = stor['host']
    port = stor['port']
    user = stor['user']
    passwd = stor['pass']
    debuglevel = stor['debuglevel']
    login = stor['login']
    starttls = stor['starttls']

    s = SMTP(host, port)
    if debuglevel:
        s.set_debuglevel(True)

    if starttls and login:
        s.ehlo()
        s.starttls()
        s.ehlo()
        s.login(user, passwd)
    elif login:
        try:
            s.login(user, passwd)
        except SMTPAuthenticationError:
            sys.stdout.write('\n------- try Auth Login again ------\n')
            s = SMTP(host, port)
            if debuglevel:
                s.set_debuglevel(True)

            s.ehlo()
            (code, resp) = s.docmd('AUTH LOGIN')
            if code != 334:
                raise SMTPAuthenticationError(code, resp)
            (code, resp) = s.docmd(encode_base64(user, eol=""))
            if code != 334:
                raise SMTPAuthenticationError(code, resp)
            (code, resp) = s.docmd(encode_base64(passwd, eol=""))
            if code != 235:
                raise SMTPAuthenticationError(code, resp)

    return s   

def sendmail(server, msg):
    address = [i for f in ('To', 'Cc', 'Bcc') if msg[f] for i in msg[f].split(',')]
    server.sendmail(msg['From'], address, msg.as_string())

def fn(options, args):
    cfg = ConfigParser()
    cfg.read(os.path.join(os.getenv('HOME'), '.LoginAccount.txt'))

    flag = 'mailClient'
    keys = ('host', 'port', 'user', 'pass', 'fr', 'to', 'debuglevel', 'login', 'starttls')
    stor = {}
    for k in keys: stor.setdefault(k, '')

    try:
        stor['host'] = cfg.get(flag, 'host')
        stor['port'] = cfg.getint(flag, 'port')
        stor['user'] = cfg.get(flag, 'user')
        stor['pass'] = cfg.get(flag, 'pass')
        stor['fr'] = cfg.get(flag, 'fr')
        stor['to'] = cfg.get(flag, 'to')
        stor['debuglevel'] = cfg.getboolean(flag, 'debuglevel')
        stor['login'] = cfg.getboolean(flag, 'login')
        stor['starttls'] = cfg.getboolean(flag, 'starttls')
    except NoOptionError: pass

    if options.addr:
        stor['to'] = options.addr
   
    s = get_smtp_client(stor)
    for arg in args:
        sys.stdout.write('sending... ' + arg)
        msg = MIMEMultipart()
        msg['From'] = stor['fr']
        msg['Subject'] = arg
        msg['To'] = stor['to']
        msg.set_boundary('===== Baby, I love you. no.0023@gmail.com =====')

        if options.atta:
            data = MIMEBase('application', 'octet-stream')
            data.set_payload(open(arg, 'rb').read())
            Encoders.encode_base64(data)
            data.add_header('Content-Disposition', 'attachment', filename = arg)
            msg.attach(data)
        else:
            b = '''<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head><body><pre>'''
            b += open(arg, 'rb').read()
            b += '''</pre></body></html>'''

            body = MIMEText(b, _subtype = 'html', _charset = 'utf-8')
            msg.attach(body)
        sendmail(s, msg)
        sys.stdout.write(' done.\n')
    s.close()

if __name__ == '__main__':

    from optparse import OptionParser
    usage = '%prog [-e addr] [-a] args...'
    parser = OptionParser(usage=usage)
    parser.add_option('-e', '--addr', dest='addr',
                      help='receive email address', metavar='ADDR')
    parser.add_option('-a', '--atta', dest='atta',
                      action='store_true', default=False,
                      help='attachment flag', metavar='atta')
    (options, args) = parser.parse_args()
    if not args:
        parser.print_usage()
        sys.exit(1)

    fn(options, args)

 

http://code.google.com/p/mylibs/source/browse/lib/Python/MyPyLib/LoginAccount.txt :

[mailClient]
host = smtp.qq.com
port = 25
user = *** # change to your login id
pass = *** # change to your login password
fr = no.0023@qq.com
to = no.0023@gmail.com
debuglevel = True
login = True
starttls = False

#[mailClient]
#host = smtp.gmail.com
#port = 587
#user = ***@gmail.com
#pass = ***
#fr = no.0023@gmail.com
#to = no.0023@qq.com
#debuglevel = True
#login = True
#starttls = True

No Comments 2009-07-10 10:31:15 by No.0023

sap rfc with python

Tags: Python, SAP

1. download rfcsdk on sap.com, download saprfc for python on http://pypi.python.org/pypi/saprfc/0.07

2. install rfcsdk and saprfc with docs

 

#! /usr/bin/env python

import pprint
import saprfc

conn = saprfc.conn(ashost='hostname', sysnr='00', client='220', lang='EN', user='xxxxx', passwd='xxxxx')
conn.connect()

print "am I connected: ", conn.is_connected()
print "sysinfo is: "
pprint.pprint(conn.sapinfo())

iface = conn.discover("RFC_READ_TABLE")
iface.query_table.setValue("TRDIR")
iface.ROWCOUNT.setValue(10)
iface.OPTIONS.setValue(["NAME LIKE 'SAPL%RFC%'"])

conn.callrfc(iface)

print "NO. PROGS: ", iface.DATA.rowCount()
#print "PROGS DATA: "
#pprint.pprint(iface.DATA.value)

# get the SAP Data Dictionary structure for TRDIR
str = conn.structure("TRDIR")

# various ways for iterating over the results in an
#  interface table
for x in iface.data.value:
  print "Doing: " + str.toHash(x)['NAME']

#print "PROGS HASH ROWS: "
#for i in iface.DATA.hashRows():
#       print "next row: ", i

conn.close()

No Comments 2009-03-05 10:10:42 by No.0023

install Python 3.0 on AIX

Tags: Python, AIX

shell:~/python-3.0.1/bin >: python3.0
Python 3.0.1 (r301:69556, Feb 27 2009, 21:48:14)
[GCC 4.0.0] on aix5
Type "help", "copyright", "credits" or "license" for more information.
>>>
shell:~/python-3.0.1/bin >:

how to install:
shell:~/tmp/Python-3.0.1 >: configure --prefix=$u/python-3.0.1 --with-gcc
shell:~/tmp/Python-3.0.1 >: make
shell:~/tmp/Python-3.0.1 >: make install

No Comments 2009-02-27 22:04:56 by No.0023

Python 3 初探,第 1 部分: Python 3 的新特性

Tags: Python

Python 3 初探,第 1 部分: Python 3 的新特性

No Comments 2009-02-06 22:59:50 by No.0023

在 Google App Engine 1.1.7 上跑 Pylons 0.9.7 RC4

Tags: Python, GAE, Pylons

版本資訊:
OS: Ubuntu 8.10
Python 2.5.4
Pylons 0.97rc4
Google App Engine 1.1.7

步驟:

svn checkout http://appengine-monkey.googlecode.com/svn/trunk/ appengine-monkey
python2.5 appengine-boot.py --paste-deploy my-app
## my-app 可改為你的想要的應用程式名稱,如:hellopylons)
>> Enter template_engine (mako/genshi/jinja/etc: Template language) ['mako']:
>> Enter sqlalchemy (True/False: Include SQLAlchemy 0.4 configuration) [False]:
>> Enter google_app_engine (True/False: Setup default appropriate
>> for Google App Engine) [False]:True
cd my-app
source bin/activate
easy_install Pylons
cd src
paster create --template=pylons MyApplication
## MyApplication 依樣可自訂其名稱
cd my-app/src/MyApplication
python setup.py develop
cd ../..
python -m pth_relpath_fixup


編輯 my-app/development.ini:

[app:the-app]
## Change this to whatever you name your application:
use = egg:MyApplication


到此與 appengine-monkey 上差不多,但接著要多幾個動作才能見到 Welcome:

一.
File ".../appengine-monkey/my-app/src/MyApplication/MyApplication/config/environment.py", line 34, in load_environment
module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
KeyError: 'cache_dir'
避免如上錯誤,編輯 my-app/src/MyApplication/config/environment.py,註解掉一行:

        ...
#module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
...


二.
VersionConflict: (WebOb 0.9 (.../google_appengine/lib/webob), Requirement.parse('WebOb>=0.9.4'))
移走 google_appengine/lib/webob 來避免這錯誤:

mv google_appengine/lib/webob/ google_appengine/webob/


即 Google Appengine 1.1.7 隨附的 webob 版本 (0.9) 未達 Pylons 0.9.7 的要求 'WebOb>=0.9.4'
註:如果你有跑其它 App Engine apps,這個 google_appengine 最好單獨就給 Pylons 使用,以免造成其它程式的問題。

好,是時候了:
/usr/bin/python2.5 google_appengine/dev_appserver.py my-app
## 我使用自己 compile 的 /usr/bin/local/python2.5 google_appengine/dev_appserver.py my-app
主要參考:
Appengine-Monkey: http://code.google.com/p/appengine-monkey/wiki/Pylons

註二:
自己 compile 的 Python 要支援 SSL 才能跑 Google App Engine,在 Ubuntu 8.10 下就是裝完 libssl-dev 後重新 make && make install。

 

from http://everydayquest.blogspot.com/2009/01/memo-of-pylons-on-google-app-engine.html

No Comments 2009-01-17 16:46:57 by No.0023

The History of Python - Introduction

Tags: Python

by gvanrossum@gmail.com (Guido van Rossum)

Python is 19 years old now. I started the design and implementation of the language on a cold Christmas break in Amsterdam, in late December 1989. It started out as a typical hobby project. Little did I know where it would all lead.

With Python's coming of age, I am going to look back on the history of the language, from the conception as a personal tool, through the the early years of community building, (If Guido was hit by a bus?), all the way through the release of Python 3000, almost 19 years later. It's been quite an adventure, for myself as well as for the users of the language.

This won't be an ordinary blog post -- it'll be an open-ended series. I may invite guest writers. I'll be touching upon many aspects of the language's history and evolution, both technical and social.

I'll start with the gradual publication of material I wrote a few years ago, when I was invited to contribute an article on Python to HOPL-III, the third installment of ACM's prestigious History of Programming Languages conference, held roughly every ten years. Unfortunately, the demands of the rather academically inclined reviewers were too much for my poor hacker's brain. Once I realized that with every round of review the amount of writing left to do seemed to increase rather than decrease, I withdrew my draft. Bless those who persevered, but I don't believe that the resulting collection of papers gives a representative overview of the developments in programming languages of the past decade.

The next destination of the draft was a book on Python to be published by Addison-Wesley. Again, the mountain of raw material that I had collected was too large and at the same time too incomplete to serve as a major section of the book, despite the editing help I received from David Beazley, a much better writer than I am.

As they tell prospective Ph.D. students, the best way to eat an elephant is one meal at a time. So today I am publishing the first bit of the elephant, perhaps still somewhat uncooked, but at least it's out there. Hopefully others who were there at the time can help clear up the inevitable omissions and mistakes. I have many more chapters, each still requiring some editing, and I expect this to be a long-running series. Therefore I am starting a separate blog title for this, unimaginatively called The History of Python. Follow the link and enjoy!

 

from http://neopythonic.blogspot.com/2009/01/history-of-python-introduction.html

No Comments 2009-01-15 09:37:29 by No.0023

New Book - Programming in Python 3

Tags: Python

Finally got my hands on the brand new "Programming in Python 3 - A Complete Introduction to the Python Language". As far as I know, this is the first print book covering Python 3.0 (Python 3000). A quick skim looked promising.

No Comments 2008-12-26 17:18:54 by No.0023

What's New in Python3.0

Tags: Python

原文:What's New in Python 3.0

这篇文章主要介绍了相比于python2.6,python3.0的新特性。更详细的介绍请参见python3.0的文档。

Common Stumbling Blocks

本段简单的列出容易使人出错的变动。

  • print语句被print()函数取代了,可以使用关键字参数来替代老的print特殊语法。例如:
    1. Old: print "The answer is", 2*2
    2. New: print("The answer is", 2*2)
    3. Old: print x,                                      # 使用逗号结尾禁止换行
    4. New: print(x, end=" ")                     # 使用空格代替换行
    5. Old: print                                         # 输出新行
    6. New: print()                                    # 输出新行
    7. Old: print >>sys.stderr, "fatal error"
    8. New: print("fatal error", file=sys.stderr)
    9. Old: print (x, y)                               # 输出repr((x, y))
    10. New: print((x, y))                           # 不同于print(x, y)!
    你可以自定义输出项之间的分隔符:
         print("There are <", 2**32, "> possibilities!", sep="")
    输出结果是:
         There are <4294967296> possibilities!

    注意:
    1. print()函数不支持老print语句的“软空格”特性,例如,在python2.x中,print "A\n", "B"会输出"A\nB\n",而python3.0中,print("A\n", "B")会输出"A\n B\n"
    2. 学会渐渐习惯print()吧!
    3. 使用2to3源码转换工具时,所有的print语句被自动转换成print()函数调用,对大项目,这是无需争论的。
  • python3.0使用字符串(strings)和bytes代替Unicode字符串和8位字符串,这意味着几乎所有使用Unicode编码和二进制数据的代码都要改动。这个改动很不错,在2.x的世界里,无数的bug都是因为编码问题。
  • map()和filter()返回迭代器(iterators)
  • dict方法keys(),items(),values()返回视图(同样是迭代器)而不是列表(list)
  • 内建的sorted()方法和list.sort()方法不再接受表示比较函数的cmp参数,使用key参数代替。
  • 1/2返回浮点数,使用1//2能得到整数。
  • repr()函数对于long整数不再包含拖尾的L,所以不加判断的去除最后一个字符会导致去掉一个有用的数字。

String and Bytes

  • 现在只有一种字符串:str,它的行为和实现都很像2.x的unicode串。
  • basestring超类已经去掉了,2to3工具会把每个出现的basestring替换成str。
  • PEP3137:新类型bytes,用来表示二进制数据和编码文本,str和bytes不能混合,需要时,必须进行显示的转换,转换方法是str.encode()(str->bytes)和bytes.decode()(bytes->str).
  • 在原始字符串(raw strings)中所有反斜线都按字面量解释,不再特殊处理Unicode转义字符。
  • PEP3112:bytes字面量,例如b"abc",创建bytes实例。
  • PEP3120:默认源文件编码为UTF-8
  • PEP3131:可以使用非ASCII标识符(然而,除了注释中贡献者的名字之外,标准库仍然只包含ASCII)
  • PEP3116:新的IO实现,API几乎100%向后兼容,二进制文件使用bytes代替strings
  • 去除了StringIO和cStringIO模块,取而代之的是io.StringIO或者io.BytesIO

PEP3101:字符串格式化的新方法

  • str.format方法(原文提到替代了%操作符,实际上,format方法和%的用法差别很大,各有所长)。

PEP3106:修补了dict的keys(),items(),values()方法

  • 删除了dict.iterkeys(),dict.itervalues()和dict.iteritems()
  • dict.keys(),dict.values()和dict.items()返回dict相关数据的引用

PEP3107:函数注解(Function Annotations)

  • 注解函数参数和返回值的标准化方法

Exception Stuff

  • PEP352:异常类必须继承自BaseException,它异常结构的基类。
  • 移除了StandardError
  • Dropping sequence behavior (slicing!) and message attribute of exception instances.
  • PEP3109:抛出异常:现在必须使用raise Exception(args)而不是原来的raise Exception, args
  • PEP3110:捕获异常,现在必须使用except Exception as identifier而不是原来的except Exception, identifier
  • PEP3134:异常链(Exception chain)。
  • 改良了一些windows不能加载模式时的异常信息,具有本地化处理。

New Class and Metaclass Stuff

  • 移除了classic class
  • PEP3115:新的metaclass语法
  • PEP3119:抽象基类。
  • PEP3129:类包装。
  • PEP3141:数字抽象基类

其他的语言变化

这里列出大多数的python语言核心和内建函数的变化。

  • 移除了backticks(使用repr()代替)
  • 移除了<>(不等号,使用!=代替)
  • as和with变成了关键字
  • True,False和None变成了关键字
  • PEP237:long不存在了,只有int,它和原来的long一样。不再支持以L结尾的数字字面量。移除sys.maxint,因为int现在已经是无限大了
  • PEP238:int相除,返回float
  • 改变了顺序操作符的行为,例如x<y,当x和y类型不匹配时抛出TypeError而不是返回随即的bool值
  • 移除了__getslice__,语法a[i:j]被解释成a.__getitem__(slice(i,j))
  • PEP3102:keyword-only arguments.在函数参数列表中,出现在*args之后的命名参数只能使用"关键字参数"的形式调用
  • PEP3104:nonlocal声明。使用nonlocal可以声明一个外部变量(不是global变量)
  • PEP3111:raw_input()改名为input(),也就是说,新的input()函数从标准输入设备(sys.stdin)读取一行 并返回(不包括行结束符),如果输入过早终止,该函数抛出EOFError,如果想使用老的input(),可以使用eval(input())代替。
  • xrange()改名为range(),range()现在不是产生一个列表(list),而是一个迭代器。
  • PEP3113:移除了"元组参数拆包(tuple parameter unpacking)"。这种写法已经不行了:
    def foo(a, (b, c)):...
    现在要这样写:
    def foo(a, b_c):
          b,c = b_c
  • PEP3114:next()重命名为__next__(),新的内建函数next()可以调用一个对象的__next__()方法。
  • PEP3127:新的八进制字面量,二进制字面量和bin()函数。你应该写0o666而不是0666,oct()函数也做了响应的改动。同样,0b1010等价于10,bin(10)返回"0b1010"。0666这种写法现在是错误的。
  • PEP3132:支持迭代器拆包。现在你可以这样写:
    a, b, *rest = some_seqence
    甚至象这样:
    *rest, a = stuff
    一般情况下,rest对象是list,而等号右边的对象是可迭代的
  • PEP3135:新的super()。你可以不适用任何参数调用super(),正确的参数和实例会被正确选择。如果使用参数,它的行为不变,和以前一样。
  • zip(),map(),filter()返回迭代器。
  • 移除了string.letters和它的朋友们(string.lowcase和string.uppercase),现在上场的是string.ascii_letters等
  • 移除了apply(),callable(),exefile(),file(),reduce(),reload()
  • 移除了dict.has_key()。使用in操作符进行测试
  • exec语句没有了,现在是exec()函数
  • 移除了__oct__()和__hex__()特殊方法。oct()和hex()方法使用__index__()
  • 移除了对__members__和__methods__的支持
  • nb_nonzero重命名为nb_bool,__nonzero__()重命名为__bool__()

Optimizations

  • 一般情况下,python 3.0比python 2.5慢33%左右。不过仍有提升空间。

模块变动(新的,改进的和废弃的)

  • 移除了cPickle模块,可以使用pickle模块代替。最终我们将会有一个透明高效的模块。
  • 移除了imageop模块
  • 移除了audiodev, Bastion, bsddb185, exceptions, linuxaudiodev, md5, MimeWriter, mimify, popen2, rexec, sets, sha, stringold, strop, sunaudiodev, timing和xmllib模块
  • 移除了bsddb模块(单独发布,可以从http://www.jcea.es/programacion/pybsddb.htm获取)
  • 移除了new模块
  • os.tmpnam()和os.tmpfile()函数被移动到tmpfile模块下
  • tokenize模块现在使用bytes工作。主要的入口点不再是generate_tokens,而是tokenize.tokenize()

Build and C API Changes

Python&rsquo;s build process和C API的改动包括:

  • PEP3118:新的Buffer API
  • PEP3121:扩展模块的的Initialization & Finalization
  • PEP3123:使PyObject_HEAD符合标准C

其他的改动和修复

在源码里分散一系列的改进和bug修复。changes log表明,从2.6到3.0,有XXX个改动和YYY的bug修复。

 

from http://jjz.javaeye.com/blog/259156

No Comments 2008-12-10 10:02:46 by No.0023

Python 3.0 on OpenBSD

Tags: Python, OpenBSD

Shell:~/tools/Py3k/bin >: ./python3.0
Python 3.0 (r30:67503, Dec  4 2008, 23:27:21)
[GCC 3.3.5 (propolice)] on openbsd4
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.uname()
('OpenBSD', 'obsd.org', '4.4', 'GENERIC.MP#0', 'i386')
>>> import sys
>>> for line in sys.path: print(line)
...

/home/Py3k/mylibs/lib/Python
/home/Py3k/tools/Py3k/lib/python30.zip
/home/Py3k/tools/Py3k/lib/python3.0
/home/Py3k/tools/Py3k/lib/python3.0/plat-openbsd4
/home/Py3k/tools/Py3k/lib/python3.0/lib-dynload
/home/Py3k/tools/Py3k/lib/python3.0/site-packages
>>>

 

 

No Comments 2008-12-04 23:35:58 by No.0023

Python 3.0 Release

Tags: Python

Python 3.0

Python 3.0 (a.k.a. "Python 3000" or "Py3k") is a new version of the language that is incompatible with the 2.x line of releases. The language is mostly the same, but many details, especially how built-in objects like dictionaries and strings work, have changed considerably, and a lot of deprecated features have finally been removed. Also, the standard library has been reorganized in a few prominent places.

Here are some Python 3.0 resources:

Please report bugs at http://bugs.python.org

Python 3.0 Release: 03-Dec-2008

Download

This is a proeuction release; we currently support these formats:

MD5 checksums and sizes of the released files:

ac1d8aa55bd6d04232cd96abfa445ac4  11191348  Python-3.0.tgz
28021e4c542323b7544aace274a03bed 9474659 Python-3.0.tar.bz2
054131fb1dcaf0bc20b23711d1028099 13421056 python-3.0.amd64.msi
2b85194a040b34088b64a48fa907c0af 13168640 python-3.0.msi

Documentation

No Comments 2008-12-04 10:16:42 by No.0023

Python FAQ from newsmth.net

Tags: Python

本FAQ内容包含:
0.Python 资源索引
1.Python的版本和下载方式
2.推荐书籍
3.推荐站点
4.Python有什么IDE
5.哪有Python电子书
6.使用easy_install安装第三方程序包
7.Python需要编译么?如何做成.exe文件
8.如何在代码中使用中文
9.Python有哪些图形库
10.一些网址
11.filter, map, reduce, zip函数
12.访问GAE,修改hosts文件的方法

0.Python 资源索引
  http://wiki.woodpecker.org.cn/mo ... on/LpyAttach2ResIdx
  大多数资料都在上面了,目录如下:
     1. Python 资源索引
         1. Py 语言自身
         2. Py 文本处理
         3. Py 数据库应用
         4. Py 网络应用
         5. Py 嵌入系统
         6. Py 多媒体支持
         7. Py 应用扩展
         8. Py 科学计算
         9. Py 行业应用
        10. Py 教育支持
        11. Py 集锦资源
     2. 资源回收

1.Python的版本和下载方式
A.至2008年10月,Python最新的版本为2.6。Python3000尚处于测试状态。Python的官方下载地址是:
http://www.python.org/download/

2.推荐书籍:
A.1、《A Byte of Python(简明python教程)》
     http://www.byteofpython.info/language/chinese/index.html
  2、《Dive into Python(Python研究)》
     http://www.woodpecker.org.cn/diveintopython/index.html
  3、《Learning Python》
  4、《Programming Python》
  第一本书非常简短,也有中文译本“简明Python教程”,是想速成(几小时)者的首选。另外在http://www.python.org/doc
很多官方的文档和教程,非常不错。

3.推荐站点:
A.1、啄木鸟社区
     http://www.woodpecker.org.cn/
  2、Python@Newsmth
     (wahahaha~~~)
  3. 中文用户组
     CPUG:
       http://python.cn
       [email]python-chinese@lists.python.cn[/email] (邮件列表) //已经停止服务,转CPyUG吧。
     CPyUG: 华蟒用户组
       https://groups.google.com/group/python-cn
     PyTUG: Python 語言台灣使用者群組
       https://groups.google.com/group/pythontw
  4. 中文论坛:
     1. Python@CU
        http://bbs.chinaunix.net/forumdisplay.php?fid=55

4.Python有什么IDE
A.Python官网有一份IDE列表,很全:
http://wiki.python.org/moin/IntegratedDevelopmentEnvironments
  如果看了上面的列表还是不知道自己该选哪个,推荐看置底的“Python IDE比较与推荐”

5.哪有Python电子书?
A.精华区x-5收录了一些经典的电子书。下载请用web方式。
  强烈推荐开放图书计划:
     http://code.google.com/p/openbookproject/ 聚集大量的Python技术图书.

另外这两个地方有很多python的电子书:
http://www.longtengwang.com/Soft/yiyong/Python/Index.html
http://www.pythonid.com/html/wendangxiazai/index.html
  想看纸质书,在书店里没有找到,那么最简单的办法是去淘宝网。

6. 使用easy_install安装第三方程序包:
A.参考:http://blog.chinaunix.net/u1/42287/showart_405102.html
        http://www.ibm.com/developerworks/cn/linux/l-cppeak3.html

  1. 安装
     wget -q http://peak.telecommunity.com/dist/ez_setup.py
     sudo python ez_setup.py
  2. 使用
     sudo easy_install CherryPy
     sudo easy_install -Z web.py-0.21.tar.gz

B. 想看看有什么第三方程序包:http://pypi.python.org/pypi

7.Python需要编译么?如何做成.exe文件?
A.Python不需要用户专门去编译它,第一次运行时,在运行过程中,Python的解析器会自动将代码编译为.pyc。一般来讲,运
行结束后不会自动删除.pyc文件。
  在Windows下,可以用py2exe等工具将代码编译为.exe文件。原理是py2exe会将必要的python解析器也打包进去。所以做成的
.exe有几M,如果有图形界面,就会有十几M,而且运行速度不会有提升。

8.如何在代码中使用中文
A.在Python2.5或之前的版本中,代码里默认是不能有中文的,包括注释。解决方法是在代码一开头加上:
# -*- coding: gbk -*-

# -*- coding: utf-8 -*-

#coding=utf-8
  具体选哪一种看具体情况。一般来讲,如果不是网络编程,统一用utf-8就OK了,包括与MySQL的交互也可以用utf-8搞定。如
果是网络编译,特别是与FTP打交道,推荐使用gbk,可以省去很多麻烦。
  注意本法没有涉及不同编码的转换。

9.Python有哪些图形库
A.常用的有tk/tcl, PyGtk,PyQt和wxPython。都是跨平台且开源的。第一个是Python自带的,但比较难用且难看。PyQt和
wxPython都漂亮好用且文档/demo很棒,目前来看PyQt4比wxPython更胜一畴。

10. 一些网址
Python:              www.python.org
ActivePython:        www.activestate.com
Stackless Python:     www.stackless.com
IronPython:          www.ironpython.com
PyPy:                pypy.org
JPython:             www.jpython.org

Django:              www.djangoproject.com
Mod_Python:          www.modpython.org
Webware:             www.webwareforpython.org
CherryPy:            www.cherrypy.org
Web.py:              webpy.org
Zope:                www.zope.org
Turbogears:          www.turbogears.org
Google AppEngine:    http://code.google.com/appengine
Twisted:             http://twistedmatrix.com
Beautiful Soup:      http://crummy.com/software/BeautifulSoup
PythonWeb:           www.pythonweb.org
JabberPy:            http://jabberpy.sourceforge.net
pyGoogle:            http://pygoogle.sourceforge.net
libgmail:            http://libgmail.sourceforge.net
pyExpect:            http://pexpect.sourceforge.net

MySQLdb:             http://sourceforge.net/projects/mysql-python
PyGreSQL:            www.pygresql.org
psycopg:             www.initd.org/pub/software/psycopg
cx_Oracle:           www.cxtools.net
SQLAlchemy:          www.sqlalchemy.org

scipy:               www.scipy.org
NumPy:               http://numpy.scipy.org
numarray:            www.stsci.edu/resources/software_hardware/numarray
matplotlib:          http://matplotlib.sourceforge.net

WxPython:            www.wxpython.org
PyGtk:               www.pygtk.org
PyQt:                http://trolltech.com/products/qt
Tkinter 3000:        http://effbot.org/zone/wck.htm
PIL:                 www.pythonware.com/products/pil
pyOpenGL:            http://pyopengl.sourceforge.net

pySoundic:           http://pysonic.sourceforge.net
pyMedia:             http://pymedia.org
FMOD:                http://www.fmod.org
pyMIDI:              http://www.cs.unc.edu/Research/assist/developer.shtml

Python Documentation Online: http://pydoc.org, http://docs.python.org
Python-cn:                   http://python.cn
Pythonic:                    http://www.woodpecker.org.cn
The Daily Python-URL:        http://www.pythonware.com/daily/index.htm
Python Package Index:        http://pypi.python.org
Planet Python:               http://www.planetpython.org
Pythonite:                   http://www.pythonite.org
Useless Python:              http://www.uselesspython.com
Python Cookbook:             http://aspn.activestate.com/ASPN/Cookbook/Python
Python Sidebar:              http://www.edgewall.org/python-sidebar
Python Source:               http://pythonsource.com

11.filter, map, reduce, zip函数
1. filter(function, sequence) 返回序列,为原序列中能使function返回true的值
    >>>a=[1,2,3,4]
    >>>filter(lambda x:x%2, a)
    [1, 3]
2. map(function, sequence, [sequence...]) 返回序列,为对原序列每个元素分别调用function获得的值.
    可以传入多个序列,但function也要有相应多的参数,如
    map(lambda x,y,z:x+y+z,range(1,3),range(3,5),range(5,7))
    计算过程为
    1+3+5=9
    2+4+6=12
    返回[9,12]
3. reduce(function,sequence,[init])
    返回一个单值为,计算步骤为 :
      * 第1个结果=function(sequence[0],sequence[1])
      * 第2个结果=function(第1个结果,sequence[2])
      * 返回最后一个计算得值
      * 如果有init,则先调用function(init,sequence[0])
      * sequence只有一个元素时,返回该元素,为空时抛出异常.
    如 reduce(lambda x,y:x+y,range(3),99) 的计算为
    99+0=99 => 99+1=100 => 100+2=102
    返回102

    注:实际使用中用内建函数sum来完成这个累加更合适,如这里等价sum(range(3),99)
4. zip用于多个sequence的循环
    questions=['name', 'quest', 'favorite color']
    answers=['lancelot', 'the holy grail', 'blue']

    for q, a in zip(questions, answers):
        print 'What is your %s ? It is %s.' % (q,a)
    输出:
    What is your name ? It is lancelot.
    What is your quest ? It is the holy grail.
    What is your favorite color ? It is blue.

12.访问GAE,修改hosts文件的方法
Shell:~/dev/AppEngine/google_appengine/n23 >: tail -n 3 /etc/hosts
209.85.171.118    n23.appspot.com
64.233.189.99   appengine.google.com
#203.208.35.100  appengine.google.com
Shell:~/dev/AppEngine/google_appengine/n23 >:

No Comments 2008-11-05 15:44:04 by No.0023

用 Python + django 10分鐘內作出一個 blog

Tags: Python, dev, Django

Ruby on Rails 的官方網站上有 15 分鐘作出一個 weblog 的 screencast,的確 demo 了 RoR 開發的快速。不過萬萬不可太迷信只有 RoR 能這麼神速,根據最近擠出一點時間看 django 的東西後,我也想先來作個「10分鐘做出 blog 的挑戰」。(由於還不太會用製作 screen cast 的軟體,所以只能用文字介紹..)這篇文章只是描述一下建構過程,所以不會介紹 django 環境的安裝設定,請讀者見諒。

稍微簡介一下 django,它是一個基於 Python 語言的 Web 開發框架(framework)。

建立 project 及 app

在 django 的環境裡,一個 project 裡可以有很多個 application,如此一來同一個 project 下的 application 便能共用同一套環境設定。所以我們先在命令列下執行 django-admin.py 來建立一個 project:

django1

先來改一下 demo/settings.py 的設定,裡面設定我們會用 sqlite3 來作資料庫的引擎,然後產生一個 demo.db 的檔案來當資料庫,再設定一些時區及 template 目錄等:

DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = 'demo.db'
...
TIME_ZONE='Asia/Taipei'
LANGUAGE_CODE='zh-tw'
...
TEMPLATE_DIRS = (
...
'.',
)

INSTALLED_APPS = (
'django.contrib.admin',
..
'demo.blog', # 等一下就會產生
)

然後在 demo 目錄下建立一個 blog 的 app:

圖片 1

然後在 demo/blog/models.py 裡建立需要的 model(DB Table):

from django.db import models

class Category(models.Model):
name = models.CharField(max_length=32)
def __unicode__(self):
return self.name
class Admin:
pass

class Article(models.Model):
title = models.CharField(max_length=64)
published_at = models.DateTimeField('date published')
content = models.TextField()
category = models.ForeignKey(Category)
def __unicode__(self):
return self.title
class Admin:
pass

然後可以看看 django 產生的 SQL DDL,確定的話就用 syncdb 來建立資料庫表格:

django3 django4

其中會要求你建立一個管理者帳號,這是為了之後進管理介面發表文章使用的帳號。完成這些動作之後,修改一下 demo/urls.py 的內容:

from django.conf.urls.defaults import *

urlpatterns = patterns('',
(r'^blog/', include('demo.blog.urls')),
(r'^admin/', include('django.contrib.admin.urls')),
)

先在 demo/blog/ 下建立一個 urls.py 的檔案,然後在命令列下輸入 python manage.py runserver,再打開瀏覽器輸入網址 http://localhost:8000/admin/ 馬上就有一個後台介面可以使用了呀!

django5 django6
發表文章的介面還蠻好用的呢

登入後你就可以直接建立 Category 及 Artical 的內容,這不就是一個現成的文章發表介面了嗎?一開始操作到現在不會超過5分鐘吧!

文章列表、單篇文章

可以發表文章之後,當然是要能夠瀏覽呀,所以我們馬上打開 demo/blog/urls.py 這個檔案,然後貼上下列的 code:

from django.conf.urls.defaults import *
from demo.blog.models import Article

info_dict = {
'queryset': Article.objects.all(),
}

urlpatterns = patterns('',
(r'^$', 'django.views.generic.list_detail.object_list', info_dict),
(r'^(?P<object_id>\d+)/$', 'django.views.generic.list_detail.object_detail', info_dict),
)

然後再分別建立 demo/blog/article_list.html 及 demo/blog/article_detail.html 這兩個檔案,分別表示文章列表及文章內容:

article_list.html:

{% if object_list %}
{% for article in object_list %}
<div class="article">
<div class="title"><a href="/blog/{{ article.id }}">{{ article.title }}</a></div>
</div>
{% endfor %}
{% else %}
<p>對不起沒有文章喔!</p>
{% endif %}

article_detail.html:

<div class="article">
<div class="title">標題: {{ object.title }}</div>
<div class="pub_date">{{ object.published_at }}</div>
<div class="content">{{ object.content }}</div>
<div class="category">發表於: {{ object.category.name }}</div>
</div>
<p><a href="/admin/blog/article/{{ object.id }}">修改</a></p>
<p><a href="/blog">BACK</a></p>

這樣很快就弄出一個很像樣的 blog (只是不能留言 XD),網址在 http://localhost:8000/blog/。

django7 django8

很快吧!當然我忽略了美工,也沒有客製化一下後台,不過 Web 開發愈來愈可怕了….真怕這種開發框架愈來愈多,老板都覺得寫網頁沒什麼了呢!

值得一提的是,django 在 runserver 之後,都會把程式碼 compile 成 pyc 檔,看起來效率應該還不錯,也許要等我多玩熟一點才能做些實驗囉。

from http://blog.ericsk.org/archives/815

 

1 Comment 2008-10-20 16:58:36 by No.0023

count_history_cmd.py

Tags: Python, dev

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import os

def f(his, n):
    lines = open(os.path.join(os.getenv('HOME'), his)).readlines()
    d = {}
    for line in lines:
        line = line.split()
        if not line: continue
        s = line[0]
        if line[0] == 'sudo':
            s = line[1]
        d[s] = d.get(s, 0) + 1

    l = sorted(d.items(), key=lambda t: t[1], reverse=True)
    for t in l[:n]:
        print '%s : %d' % (t[0].ljust(16), t[1])

if __name__ == '__main__':
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option('-f', '--file', dest='f', default='.history',
                      help='the history file', metavar='FILE')
    parser.add_option('-c', '--count', dest='c', type='int', default='30',
                      help='for display count', metavar='COUNT')
    (options, args) = parser.parse_args()
    f(options.f, options.c)

 

运行结果:

Shell:~ >: count_his_cmd
cd               : 4895
ls               : 4533
vi               : 988
man              : 679
hitfm            : 583
cat              : 532
ifconfig         : 414
ant              : 401
rm               : 386
lt               : 349
ll               : 341
tmp              : 340
svn              : 333
tlist            : 332
top              : 311
my               : 292
exit             : 278
run              : 277
unlcall          : 249
pkg_list         : 249
glib             : 242
locate           : 235
shutdown         : 226
bbs.sh           : 220
check            : 216
ping             : 215
pkill            : 198
mv               : 196
vpn              : 190
sock             : 186
Shell:~ >:

 

from http://code.google.com/p/mylibs/source/browse/trunk/tools/Python/count_history_cmd.py

No Comments 2008-10-15 22:21:44 by No.0023

Python 2.6 final release

Tags: Python
We are pleased to announce the release of Python 2.6 (final), a new production-ready release, on October 1st, 2008.

There are a huge number of new features, modules, improvements and bug fixes. For information on what's changed, see:

  • Andrew Kuchling's guide to What's New in Python 2.6.
  • NEWS file contains a listing of everything that's new in each alpha, beta, and release candidate of Python 2.6.
  • PEP 361.

Please report bugs at http://bugs.python.org

See also the license.

Python 2.6 Released: 01-Oct-2008

Download

This is a production release; we currently support these formats:

MD5 checksums and sizes of the released files:

837476958702cb386c657b5dba61cdc5  10957859  Python-2.6.tar.bz2
d16d29a77db2cd3af882a591f431a403 13023860 Python-2.6.tgz
fe34764ad0027d01176eb1b321dd20c5 14503936 python-2.6.amd64.msi
6c62c123d248a48dccbaa4d3edc12680 14173184 python-2.6.msi
29a1a22f8d9fd8a4501b30d97fbee61c 23593748 python-2.6-macosx2008-10-01.dmg

The signatures for the source tarballs above were generated with GnuPG using release manager Barry Warsaw's public key which has a key id of EA5BBD71. The Windows installers was signed by Martin von L&ouml;wis' public key which has a key id of 7D9DC8D2. The signature on the Mac disk image was signed by Benjamin Peterson's public key which has a key id of A4135B38.

Vista Note

Administrators installing Python for all users on Windows Vista either need to be logged in as Administrator, or use the runas command, as in:

runas /user:Administrator "msiexec /i <path>\<file>.msi"

Documentation

The documentation has also been updated. You can browse the HTML on-line or download the HTML

No Comments 2008-10-03 12:39:53 by No.0023

PyConUK 2008

Tags: Python, dev

No Comments 2008-09-22 15:33:45 by No.0023

An enhanced interactive Python shell

Tags: Python, dev

Shell:~/tmp >: rpm -qi ipython
Name        : ipython                      Relocations: (not relocatable)
Version     : 0.8.2                             Vendor: Fedora Project
Release     : 1.fc9                         Build Date: 2007年12月13日 星期四 09时21分06秒
Install Date: 2008年09月19日 星期五 12时11分45秒      Build Host: ppc4.fedora.phx.redhat.com
Group       : Development/Libraries         Source RPM: ipython-0.8.2-1.fc9.src.rpm
Size        : 4124412                          License: BSD
Signature   : DSA/SHA1, 2008年04月11日 星期五 04时10分26秒, Key ID b44269d04f2a6fd2
Packager    : Fedora Project
URL         : http://ipython.scipy.org/
Summary     : An enhanced interactive Python shell
Description :

IPython provides a replacement for the interactive Python interpreter with
extra functionality.

Main features:
 * Comprehensive object introspection.
 * Input history, persistent across sessions.
 * Caching of output results during a session with automatically generated
   references.
 * Readline based name completion.
 * Extensible system of 'magic' commands for controlling the environment and
   performing many tasks related either to IPython or the operating system.
 * Configuration system with easy switching between different setups (simpler
   than changing $PYTHONSTARTUP environment variables every time).
 * Session logging and reloading.
 * Extensible syntax processing for special purpose situations.
 * Access to the system shell with user-extensible alias system.
 * Easily embeddable in other Python programs.
 * Integrated access to the pdb debugger and the Python profiler.

 

一定要装上这个...

No Comments 2008-09-19 12:38:02 by No.0023

开源网络蜘蛛spider(转载)

Tags: Python, dev, others

spider是搜索引擎的必须模块.spider数据的结果直接影响到搜索引擎的评价指标.

第一个spider程序由MIT的Matthew K Gray操刀该程序的目的是为了统计互联网中主机的数目

spider定义(关于Spider的定义,有广义和狭义两种).

  • 狭义:利用标准的http协议根据超链和web文档检索的方法遍历万维网信息空间的软件程序.
  • 广义:所有能利用http协议检索web文档的软件都称之为spider.

其中Protocol Gives Sites Way To Keep Out The 'Bots Jeremy Carl, Web Week, Volume 1, Issue 7, November 1995 是和spider息息相关的协议,可以参考robotstxt.org.

Heritrix

Heritrix is the Internet Archive's open-source, extensible, web-scale, archival-quality web crawler project.

Heritrix (sometimes spelled heretrix, or misspelled or missaid as heratrix/heritix/ heretix/heratix) is an archaic word for heiress (woman who inherits). Since our crawler seeks to collect and preserve the digital artifacts of our culture for the benefit of future researchers and generations, this name seemed apt.

语言:JAVA, (下载地址)

WebLech URL Spider

WebLech is a fully featured web site download/mirror tool in Java, which supports many features required to download websites and emulate standard web-browser behaviour as much as possible. WebLech is multithreaded and comes with a GUI console.

语言:JAVA, (下载地址)

JSpider

A Java implementation of a flexible and extensible web spider engine. Optional modules allow functionality to be added (searching dead links, testing the performance and scalability of a site, creating a sitemap, etc ..

语言:JAVA, (下载地址)

WebSPHINX

WebSPHINX is a web crawler (robot, spider) Java class library, originally developed by Robert Miller of Carnegie Mellon University. Multithreaded, tollerant HTML parsing, URL filtering and page classification, pattern matching, mirroring, and more.

语言:JAVA, (下载地址)

PySolitaire

PySolitaire is a fork of PySol Solitaire that runs correctly on Windows and has a nice clean installer. PySolitaire (Python Solitaire) is a collection of more than 300 solitaire and Mahjongg games like Klondike and Spider.

语言:Python , (下载地址)

The Spider Web Network Xoops Mod Team     

The Spider Web Network Xoops Module Team provides modules for the Xoops community written in the PHP coding language. We develop mods and or take existing php script and port it into the Xoops format. High quality mods is our goal.

语言:php , (下载地址)

Fetchgals

A multi-threaded web spider that finds free porn thumbnail galleries by visiting a list of known TGPs (Thumbnail Gallery Posts). It optionally downloads the located pictures and movies. TGP list is included. Public domain perl script running on Linux.

语言:perl , (下载地址)

Where Spider


 

The purpose of the Where Spider software is to provide a database system for storing URL addresses. The software is used for both ripping links and browsing them offline. The software uses a pure XML database which is easy to export and import.

语言:XML , (下载地址)

Sperowider

Sperowider Website Archiving Suite is a set of Java applications, the primary purpose of which is to spider dynamic websites, and to create static distributable archives with a full text search index usable by an associated Java applet.

语言:Java , (下载地址)

SpiderPy

SpiderPy is a web crawling spider program written in Python that allows users to collect files and search web sites through a configurable interface.

语言:Python , (下载地址)

Spidered Data Retrieval

Spider is a complete standalone Java application designed to easily integrate varied datasources. * XML driven framework * Scheduled pulling * Highly extensible * Provides hooks for custom post-processing and configuration

语言:Java , (下载地址)

webloupe

WebLoupe is a java-based tool for analysis, interactive visualization (sitemap), and exploration of the information architecture and specific properties of local or publicly accessible websites. Based on web spider (or web crawler) technology.

语言:java , (下载地址)

ASpider

Robust featureful multi-threaded CLI web spider using apache commons httpclient v3.0 written in java. ASpider downloads any files matching your given mime-types from a website. Tries to reg.exp. match emails by default, logging all results using log4j.

语言:java , (下载地址)

larbin

Larbin is an HTTP Web crawler with an easy interface that runs under Linux. It can fetch more than 5 million pages a day on a standard PC (with a good network).

语言:C++, (下载地址)

 

from http://www.wujianrong.com/archives/2008/09/spider.html

No Comments 2008-09-10 08:44:01 by No.0023


标签: Python 共有文章28篇 第(1/2)页 首页 上一页 1 ... 下一页 末页