Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Wednesday, April 15, 2015

WSGI vs uWSGi

Ok, guys this confusion is because of lack of detail from several sources, and the naming of these protocols, and what WSGI actually is.

Summary:

1. WSGI and uwsgi both are protocols, not servers. It is used to communicate with web servers for load balancing and especially to take advantage of extra features that pure HTTP can not provide. So far Nginx and Cherokee have implemented this protocol.

2. uWSGI is a server and one of the protocols it implements is WSGI. WSGI is a Python specification. There are several implementations of the WSGI specification and it's intended to be used for more than just application servers/web servers, but there are quite a few WSGI application servers (ie. CherryPy, which also happens to have a production ready WSGI compliant web server, if you weren't confused enough already!).

3. Comparing uwsgi to WSGI is comparing oranges to apples.

Reference:

http://stackoverflow.com/questions/7739810/wsgi-vs-uwsgi-with-nginx
http://flask.pocoo.org/docs/deploying/uwsgi/
http://nichol.as/benchmark-of-python-web-servers

Saturday, March 7, 2015

學習和開發 Python 的好幫手

慣用 IDE 的人會推 Eclipse + PyDev, 網路上有不少教學文章。我則是慣用 VIM IPython

這裡有我針對 Python 設的 vim 設定檔, 有興趣用的人可以撿需要的部份用, 或是直接複制整個 .vim 和 .vimrc 也行 (若你原本沒設 .vim 和 .vimrc):

$ git clone git://github.com/fcamel/configs.git
$ cp -r configs/.vim ~
$ cp configs/.vimrc ~

推薦讀 IPython Tip Sheet 學習使用 IPython, 花個十分鐘將可獲得兩倍以上的學習速度。我常最用的指令是 ? 和 ??, 分別會秀出物件 (函式) 說明和原始碼。它的運作原理很簡單, 因為在 Python 的世界裡, 所有東西都是物件, 而物件的 __doc__ 欄位存有文件, __file__ 欄位則存有載入的檔案路徑。因此 IPython 可以輕易地讀入文件和原始碼。

如此一來, 在 screen 裡開兩個 terminal, 一個開 IPython; 一個開 VIM。想試什麼簡單程式就在 IPython 裡試, 有疑問就用 ? 和 ?? 查。在 VIM 裡可按 F10 執行內容, 方便試較長一些的程式。實際開發時則在 VIM 裡切兩個視窗, 一個寫 unit test, 一個寫 software-under-test。在 unit test 的視窗裡按 F10 執行程式, 有錯就切到 software-under-test 的視窗改。若有錯不知錯在那想了解物件內容, 則在 unit test 裡呼叫 IPython [1], 進入 IPython 內了解詳情, 寫起來很有效率。



Reference:

http://fcamel-life.blogspot.ca/2010/03/python.html

學 Python 的入門書

常看到有人問這問題,想說來寫篇心得,省得重覆回一樣的問題。
我在學 Python 前已學過別的程式語言,所以想找針對已學過程式的人的書。一開始翻許多人推薦的《Learning Python》,發現它是針對沒學過程式的人,有太多篇幅在介紹基本觀念 (如 if 是什麼 ),翻沒幾頁就沒耐性看下去。而《Programming Python》又太厚了,於是找別本書。
後來 Scott 推薦我看《Python Essential Reference》 (目前出到第四版,包含 Python 2.6 的新功能),我一看就驚為天人,「if、elif、else」只有一頁!內容包含完整語法,以及特殊情況 ( 若 if 之後想放空的 statement ,要用 pass )。沒錯,這就是我要的書,去蕪存菁地讓讀者立即掌握 Python 的語法。附帶一提,Scott 明明已學會了,竟然還買了一本用來傳教,真是面惡心善的好學長。
看完這本後,有時查些 Python 觀念或函式名稱,發現常連到《Dive into Python》,才發覺這本也滿有名的,而且還有完整免費的網頁版。於是又找時間看了《Dive into Python 3》,順便了解 Python 3 有啥有趣的東西。發覺這本書超合我胃口,直接用完整的例子說明語法,在學到語法的同時,也明白怎麼實際使用這些語法。有些書就像辭典一般,提了很正式的語法,讀起來很累,讀完卻不知能怎麼用它們。《Dive into Python 3》不但用生動的實例避免這個問題,並進一步深入淺出地介紹運作細節。而且還提到如重構、單元測試等寫軟體的重要觀念,又有詳細的 Python 2 和 3 的比較。若只對 Python 2 有興趣也沒關係,大部份語法仍適用於 Python 2.6 (2.6 是承接 Python 2 和 3 的橋樑)。
總結來說,若你沒學過程式語言,我不知道能推薦什麼書藉。或許可以參考《Python Programming: An Introduction to Computer Science》,這是 MIT 6.00: Introduction to Computer Science and Programming 的參考書,該課程用 Python 教沒寫過程式的學生學會電腦科學家的思考方式。若有學過程式語言,《Python Essential Reference》或《Dive into Python 3》都值得一看。除了學會 Python 之外,兩者提供不同的額外內容,都看也不會浪費時間。

延伸閱讀

學會 Python 基本語法後,可以先看這幾篇了解如何寫出更道地的 Python。道地的 Python 程式不但易讀、易維護,通常也表示更有效率:
再來,可以到《Python Essential Reference》作者 David Beazley 的網站挖寶,像是:
另外若對 design patterns 有興趣,可以看 Google 員工 Joe Gregorio 寫的(The Lack of) Design Patterns in Python
《Python Cookbook》也有不少經典寫法,不過該書有點舊了 (到 Python 2.4),有些方法已用不到,看的時候要挑一下。
原以為延伸閱讀應該沒多少東西,沒想到我拉拉雜雜也看了不少文件,整理到後來就累了。不知何時 Python 才會像 Java 有本《Effective Python》,一本搞定大部份的注意事項和經典寫法。

備註:設定開發環境


Reference:

http://fcamel-fc.blogspot.ca/2010/02/python.html

Python 的特別之處 (1)

從新手的眼中來看 Python,比較能看出 Python 和其它語言不同之處。最近有機會幫別人快速上手 Python,就順便整理一下我從中發覺 Python 較為突出的優點。

list、dictionary and string

平時 coding 最常用到的 container 就是 list 和 dictionary,另外也會常用到字串操作,Python 提供方便的方法來操作它們。string 可看成一個有實作 list 介面的類別,一些常用操作像是 slice:"abcd"[1:3] 回傳 "bc";負數的索引: "abcd"[-1] 回傳 "d";直接和 for-loop 整合在一起:
In [1]: for ch in "abcd":
  ....:         print ch
  ....:
a
b
c
d
讓存取這些常用資料型態輕鬆許多。

iterator

使用 iterator 比傳統的 for (i=0; i 來得清楚,Python 針對 iterator 下了不少工夫,提供好用的輔助函式,像是 enumerate 補足需要用到 index 的情況:
In [2]: for i, n in enumerate([1, 3, 5]):
  ....:     print i, n
  ....:
0 1
1 3
2 5
使用 zip 整合多個 list:
In [3]: names = ["John", "Marry", "Tom"]
In [4]: sexes = ["Male", "Female", "Male"]
In [5]: for name, sex in zip(names, sexes):
  ....:     print name, sex
  ....:
John Male
Marry Female
Tom Male

map, filter and reduce

任何使用過 map 的人,都會喜歡 map 輕巧的用法,來看幾個例子:
In [1]: map(int, ["12", "37", "999"])
Out[1]: [12, 37, 999]
In [2]: map(str, [12, 37, 999])
Out[2]: ['12', '37', '999']
int 是一個函式,將傳入的物件轉成整數;str 則是轉成字串。使用 map 可以將一個 iterator 轉為另一種 list。
另一個常見的情境是,從一個 list 裡篩選出需要的物件,比方說只留下偶數:
In [1]: numbers = [1, 2, 3, 4, 5]
In [2]: filter(lambda x: x % 2 == 0, numbers)
Out[2]: [2, 4]
或像 filter(lambda s: s.endswith('.py'), file_names) 只留下結尾為 ".py" 的字串。
除 map 和 filter 的重心放在轉換 list 之外,reduce 則是將 list 匯整成一個物件。有了這些函式,就能任意的操作 list,用以匯整或擴散資料容器。
比方說將一串數字加起來:
In [1]: numbers = [1, 2, 3, 4, 5]
In [2]: reduce(lambda x, y: x + y, numbers, 0)
Out[2]: 15
上面這個例子可以用內建的 sum 取代,來看另一個複雜點的例子,將一串 0、1 值合成一個整數:
In [1]: bits = [0, 1, 0, 0, 1]  # bits[i] 的值表示 2^i 的系數

In [2]: reduce(lambda x, (i, b): x | (b << i), enumerate(bits), 0)
Out[2]: 18

list comprehension

map 和 filter 雖然方便,要用到 lambda 或是混合使用時就沒那麼好讀了。Python 提供一個重量級的武器 list comprehension 來解決這問題。比方說留下偶數並乘以三再加一:
In [1]: numbers = [1, 2, 3, 4, 5]

In [2]: [n * 3 + 1 for n in numbers if n % 2 == 0]
Out[2]: [7, 13]
綜合以上的語法,可以輕鬆地寫出易懂的 quick sort
def qsort(numbers):
    if len(numbers) <= 1:
        return numbers                                                                                     
    pivot = numbers[0]
    rest = numbers[1:]
    smaller = [n for n in rest if n <= pivot]
    larger = [n for n in rest if n > pivot]
    return qsort(smaller) + [pivot] + qsort(larger)
對於習慣 C、C++、Java 世界的人來說,應該不曾看過這麼直覺易懂的quick sort 吧。

tuple

tuple 是一個很妙的資料結構,它和 list 的主要差別是它是唯讀的,Python 裡鮮少有這種唯讀物件。不過它較易發覺的好處是被用在 Python 的parallel assignment 和函式傳回值。
於是在 Python 裡可以這麼寫:
a, b = b, a # swap
Python 在看到 b, a 時會產生一個 tuple 表示 (b, a),再透過 tuple 達到parallel assignment
函式也可以一次「傳回多個結果」:
In [1]: def divide_and_mode(a, b):
   ...:     if b == 0:
   ...:         return None, None
   ...:     return a / b, a % b
   ...:

In [2]: divide_and_mode(7, 3)
Out[2]: (2, 1)

In [3]: a, b = divide_and_mode(7, 3)

In [4]: a
Out[4]: 2

In [5]: b
Out[5]: 1
原理一樣是先轉成 tuple 再傳回,再視等號左側放什麼,決定要存成 tuple 或做 parallel assignment

2012-01-25 更新

應該沒什麼力氣更新續篇,在這裡簡短描述一下,有興趣的人可以找看看相關介紹。

with

在 Python 2.6 後,支援用 with 管理資源。像讀檔案可以用 with 的方式寫:
# 印出所有使用者的 id
with open('/etc/passwd') as fr:
    for line in fr:
        print line.split(':')[0]  
在進入 with 的 block 前,會呼叫 file object 的 __enter__ 以獲得 file descriptor;在離開 block 前會呼叫 __exit__ 關掉 file descriptor。即使中間呼叫了 sys.exit() 或丟出 exception,仍會執行到 __exit__,不用擔心會漏關。方便用在許多情境 (比方說 lock / unlock、自動 flush output buffer),易讀易用。

內建常用函式庫

除上述的基本資料結構和 string 外,還有 sqlitejson等。

簡單不易出錯的語法

舉幾個寫 C 可能發生的問題,但在 Python 的語法下則不會發生:
if (condition);
{
    // BUG!! 這裡的程式一定會被執行
}
if (x < 60)
    number_of_fail++;
    total_fail_score += x; // BUG!! 這行每次都會執行
另外,由於 Python 的 condition 只能是 expression,不能是 assignment。不會有 if (x -= 3 < 0) 這種 bug。

Reference:

http://fcamel-fc.blogspot.ca/2011/08/python-1.html

Friday, December 16, 2011

Hello World Python GUI with Tkinter on CentOS and FreeBSD

Background


Tkinter is a Python binding to the Tk GUI toolkit. It is the standard Python interface to the Tk GUI toolkit[1] and is Python's de-facto standard GUI,[2] and is included with the standard Windows install of Python.

As with most other modern Tk bindings, Tkinter is implemented as a Python wrapper around a complete Tcl interpreter embedded in the Python interpreter. Tkinter calls are translated into Tcl commands which are fed to this embedded interpreter, thus making it possible to mix Python and Tcl in a single application.
Python 2.7 and Python 3.1 incorporate the "themed Tk" ("ttk") functionality of Tk 8.5.[3][4] This allows Tk widgets to be easily themed to look like the native desktop environment in which the application is running, thereby addressing a long-standing criticism of Tk (and hence of Tkinter).
There are several popular GUI library alternatives available, such as wxPython, PyQt and PyGTK.

From:
http://en.wikipedia.org/wiki/Tkinter

On CentOS 6.1
# python --version
Python 2.6.6

# yum list | grep lib-tk
python-matplotlib-tk.i686 0.99.1.2-1.el6 @base

# yum install python-matplotlib-tk.i68

# find /usr/lib/python2.6/ -name Tkinter.py
/usr/lib/python2.6/lib-tk/Tkinter.py

On FreeBSD 8.2
# cd /usr/ports/x11-toolkits/py-tkinter/ ; make install clean

# python --version
Python 2.7.2

# find /usr/local/lib/python2.7/ -name Tkinter.py
/usr/local/lib/python2.7/lib-tk/Tkinter.py

Hello World
# vim ~/tmp/hello_world.py
#!/usr/bin/python
# -*- coding: iso-8859-1 -*-

from Tkinter import *

root = Tk()

w = Label(root, text="Hello, world!")
w.pack()

root.mainloop()

# python ~/tmp/hello_world.py

Reference:
http://sebsauvage.net/python/gui/
http://www.tkdocs.com/tutorial/index.html

convert python scripts to .exe executable file

convert python scripts to .exe executable file

py2exe -
http://www.py2exe.org/

py2app -
http://svn.pythonmac.org/py2app/py2app/trunk/doc/index.html

cx_Freeze - is a set of scripts and modules for freezing Python scripts into executables in much the same way that py2exe and py2app do. Unlike these two tools, cx_Freeze is cross platform and should work on any platform that Python itself works on. It requires Python 2.3 or higher since it makes use of the zip import facility which was introduced in that version.

// supports Python 3.2

http://cx-freeze.sourceforge.net/

===
scru: If you know C, you can make a bootstrap app that embeds the interpreter and then runs your script. I think it's just a few lines of code, but you would have to distribute python30.dll alongside the parts of the standard library that your program uses.
===
Nicholas Knight: There's nothing stopping you from including a prebuilt Python environment in your package/installer and either creating an appropriate shortcut to launch the Python app, or creating a separate executable that launches the Python app (or even linking the Python interpreter into the executable and using it like that...). It just takes some more effort making sure you've got all the right pieces (like .dlls) where they need to be.

Remember, Python doesn't have to be "installed" per se, you just need to make sure it knows where to find everything (e.g. set the appropriate environment variables like PYTHONPATH in whatever launcher you're using).
===
Reference:
http://www.daniweb.com/software-development/python/threads/192343
http://stackoverflow.com/questions/3447093/what-technologies-exist-to-create-stand-alone-executables-for-python-3

Thursday, October 30, 2008

Python 與 Zope 入門

Python 與 Zope 入門

前言

如果你是程式語言的新手,恭喜你,因為這裡介紹的正是合適入門的開放源碼語言工具;如果你是其他語言的老手,同樣恭喜你,因為這裡介紹的內容,很可能是你正在尋找的出路…


對於已經愛上開放源碼的朋友來說,每個人都有屬於自己和開放源碼之間的機緣與情愫,以我為例,當初是因為對搖滾樂的熱愛,而一步一步地走進這片自由開放的天地。

先讓時間回到 1995 年,那時候我是一個泡在電腦教室裡,一待就是十小時的政大學生,除了迷上 TANet 所流行的校園 BBS 之外,Internet 上有趣的新鮮玩意,還有 Gopher、Newsgroup、IRC 等。在新學期開始沒多久,我依舊快樂地享受網路世界的冒險之旅,無意間看到在電腦教室外行色匆匆的鳥合 (陳彩合),他跟我說道「等一下我會介紹 World Wide Web,你有沒有興趣來聽?」當然囉,難得鳥合不再開口閉口講我聽不懂的 sendmail,當下跟著進教室聽他介紹 WWW 這個「網路新名詞」。

初見 WWW 的感受,對我啟迪很大,原本想要拜師學 C 語言以及當 BBS 站長的我,沒多久就跟師父 - 黃志中講,「我覺得 WWW 才是值得投入的千秋大業啊」。現在來看,猶能感受當初那股「不知天高地厚」的傻勁。

沒多久,我就利用自己在學校宿舍的 486 PC,以 Linux 和 Apache 架起了一個陽春的 Web Server,內容就是介紹我最喜愛的搖滾樂團,期間還收到一些令我驚訝的回應與鼓勵。接著,我和網友死黨們,在政大校園裡組了「網路應用推廣社團」,打 算仿照交大 CCCA 運作模式,以政大學生宿舍、學生社團、行政服務為先期焦點,介紹各式網路應用並協助其普及。

後來的事就不難想像啦,因為自己花了一些時間在玩電腦網路,大學畢業前,就打算從財管系再換跑道到資管研究所,而且從原本想要當 Unix 維修工程師,變成現在的 Open Source 工作者。好啦,如果要用 500 字講自己和開放源碼的因緣,就是這些了。

初識 Python 與 Zope

在 2000 年底之際,我想要尋找一個 WebDAV 伺服器的開放源碼實作品,無意間遇上了 Zope 這套 Web Application Server,在 Zope 的簡介資料中,發現它是以 Python 程式語言所開發完成,因此機緣,讓我踏上學習與享受 Python 的這條路。Python 與 Zope 都是非常值得介紹及推廣的開放源碼工具,我很高興能夠利用這個機會,將自己所知的心得經驗分享給同好。相信 Python 的易學易用,能讓新手輕鬆上路,享受撰寫程式的樂趣和成就感,Python 廣大的模組功能支援,能讓擁有「懶惰美德」的程式人員,快速搞定原本惱人的開發需求。如果你是尋求大型網站系統解決方案的程式人員、資料庫管理人員,或是 內容管理人員,Zope 系統絕對是值得你留意及投入的開放源碼應用工具。

難以寫出優美程式碼的語言,勢必也難以寫出優秀的程式碼。
A language that makes it hard to write elegant code makes it hard to write good code. -- Eric S. Raymond

什麼是 Python ?

從技術層面來看,Python 是一種物件導向式 (object-oriented) 程式語言的名稱,它具備直譯式 (interpreted)、互動式 (interactive)、模組化 (modular) 的功能及特色,經常被拿來與 Visual Basic、Perl、Java 等程式語言相提並論。Python 語言的作者是Guido van Rossum,最早在 1990 年之際開始進行發展,其程式實作迄今已普遍存在於各式作業平台上,例如 Linux、UNIX、Windows、Mac、OS/2 等。其他相關的延革資訊,請參考列表1所示。

圖1 Python 語言之父 -- Guido van Rossum

Python 同時也具備動態定型 (dynamic typing) 的特性,程式人員不需要宣告變數型態,其內建物件型態 (built-in object type) 包括 list、dictionary、string、tuple等,能夠滿足最常見、最重要的應用需求,其內建的工具 (built-in tool) 包括 slicing、concatenating、sorting、mapping 等,能夠協助程式人員專注於處理最關鍵的技術議題,其內建的函式庫包括網路服務 (http、ftp)、檔案處理 (regular expression、HTML、XML、socket) 等,在圖形介面的選擇上,較引入注目的包括有 wxPython (如圖2所示)、PyGTK (如圖3所示)、PyQt 等,此外還有豐富的線上文件,可參見列表2。

圖2 以 wxPython 示範 Unicode 應用服務

圖3 PyGTK 程式示範畫面

Python 語言的執行檔格式 (常見之執行檔副檔名為 .pyc),與 Java 語言的 byte code 格式類似,byte code 執行檔具跨平台特性,例如可從 Windows 上複製到 Linux 直接可用,反之亦然。值得一提的是,它可以和其他語言進行結合,具有良好的「黏膠」(gluing)功能,例如透過「擴充機制」(extending) 來讓 Python 執行另一個 C++ 程式,透過「內嵌機制」(embedding) 來讓 Python成為 C/C++ 等應用軟體的一部份。如此一來,開發大型應用軟體時,使用 Python可以達到快速開發 (rapid model and development) 的效果,同時也內嵌 C/C++ 程式,以便改善執行效率的瓶頸點。

從 Python 2.1 開始,其核心納入了 PyUnit 模組,協助程式人員利用它來體驗 Extreme Programming (XP),同時,XP 的精神也很自然地能夠吸引 Python 程式人員。以 Zope 開發社群為例,程式人員經常巡迴舉辦世界各地的「衝鋒編程聚會」(Sprint Coding Party),由資深的核心軟體開發人員擔任「教練」,透過小組型式,讓程式人員在最短的時間內完成特定的程式開發目標。[註1]

從非技術的角度來說明,Python 是一種高階的通用式 (general purpose) 手稿 (scripting) 語言,藉由包裝良好的套件檔案 (如 Windows 的 Installer 或 Linux的 rpm 工具程式),新手很容易就能安裝最新版的 Python 工具,如圖4所示。對於一時之間離不開 Windows 平台的朋友,我特別推薦使用 cygwin 工具軟體,其內附的 Python 程式及操作環境,能夠提供相當完整的基本服務,如圖5所示。

圖4 Windows 平台上的 PythonWin 示範畫面

圖5 cygwin 裡的 Python 操作示範畫面

Python 具有語法簡易、結構清楚的特色,在撰寫 Python 程式碼的過程中,很容易享受到「碼隨意至」的直覺快感,不會有思路阻塞的困擾。同時,它利用縮排方式,協助程式人員能夠對原始碼有一目瞭然的感受,有助於 新手快速入門起步。如果你想要找尋類似 Perl 社群的 CPAN 程式碼倉庫,參考許多 Python 好手所貢獻的原始碼,那麼別錯過 SourceForge.net、Freshmeat.net、Starship.Python.net 或 Vaults of Parnassus 網站,對於想要學習程式的朋友而言,裡頭稱得上是知識的大寶山呢。

開放源碼授權

絕大部分的 Python 程式為 Python 軟體基金會 (Python Software Foundation )所有,但整個 Python 程式皆受 Python License 規範 [註2]。其授權方式主要特色包括:

  • 自由使用: 商業或非商業皆可,內嵌或擴充都不用付授權費。
  • 自由散佈: 以原始碼或二進位元 (binary) 方式散佈原版或修改過的 Python 都可以,也可以用二進位元方式散佈你的 Python 擴充模組。
  • 在你散佈的版本中,不可以移除 Python 軟體基金會的版權宣告。
  • 開放源碼創進會 (Open Source Initiative) 已認證 Python License 為開放源碼的授權條款。
  • 自由軟體基金會 (Free Software Foundation) 也認定 Python License 和 GPL 相容。

    開放源碼世界的程式語言選項很多,Python 確實只是其中的一個優秀選擇,對我而言,選擇它最關鍵的原因有二,一來 Python 是「極佳的入門踏腳石」,二來 Python 具有殺手級應用軟體 - Zope (甚至是 Plone 這樣的工具)。

    我個人稱不上是一位軟體工程師,平常若有編寫程式的機會,大抵是自己餘暇的娛樂享受,但我能夠體會程式人員想要與人分享編寫程式甘苦的心情。Python 與 Zope 社群所營造的活潑、和諧、開放氣氛,是促使我要把這個好工具介紹給身邊朋友的動力。

為什麼要學 Python ?

長期以來,台灣以資訊硬體的代工生產成就聞名於世,但在軟體方面的發展,目前仍位居全球的邊緣化位置。全球的華人都很聰明勤奮,台灣人也呈現類似的 特質,如何從這樣的良好特質出發,讓台灣的軟體發展現況有所改善呢? 此刻來看,華人在軟體部份的投入,主要也是以「代工型式」進行,拿美國的大型軟體公司或網路公司做例子,其軟體工程部門,很多就是印度或華人工程師,他們 在美國的創業環境中,以優異的「數理能力」與「語文溝通訓練」為基礎,成為軟體公司裡「編程部隊」的主要成員。

對照上述的例子,在台灣有心投入軟體發展的朋友,還能多做些什麼呢? 至少有個工作項目,就是推廣程式語言的學習與應用,而 Python 語言就是我認為極佳的入門選擇。一個軟體工程師的養成,大抵需要從「數理邏輯基礎」、「語文溝通能力」紮根,並且具備「樂於不斷學習與創作」的人格特質, 應用 Python 語言及其開發環境,能夠讓一位軟體工程師立於非常理想的學習起點。

從教育紮根

老師對學生具有相當大的潛移默效果,台灣的資訊教育工作人員,多數期望能夠引導學生「合情合理合法」地獲得學習工具及資源,但坊間能夠提供給老師的 教材種類及型式還不夠多樣,以致老師們只能牽就於特定廠商所提供的教材手冊,甚至間接影響學生使用了非法取得的程式開發工具,造成老師與學生雙方的困擾。 這部份的問題,可以嘗試改用開放源碼的程式開發環境及工具來避免,因為開放源碼授權的軟體,非但可以免費或低價取得,也歡迎再複製、修改、散佈給其他人, 非常有利於教學研究的場合。

不過,開放源碼的程式設計工具書,大抵也還有不足之處,目前坊間以 PHP 或 Perl 的應用類書籍居多,英文版的 Python 書籍 (參見列表3),質與量雖然也開始增加,但中文的書籍、網路資源及介紹專文,都有許多值得提昇之處。在此,這篇文章算是我個人的棉薄貢獻,真心期盼有拋磚 引玉之效,邀請更多同好共同投入,可以參與的項目包括翻譯計畫、同好聚會、技術交流、訓練課程等。[註3]

Python 這項工具擁有許多迷人的特色,整理如列表4所示,目前在開放源碼世界裡相當受到好評,許多活躍的 Python開發人員,是來自於歐洲、美加、澳洲等地,大陸地區最近也開始活絡起來。雖然台灣的市場現況,Visual Basic 或 Java 似乎還是商業主流選擇,但仍然並未影響我個人的願望,就是要在華人地區推廣 Python 程式語言,當作中學生的程式設計入門工具,因為從 Python 入門之後,要進一步去學習與應用 C/C++ 或 Java,也都是相當輕鬆自然的事,不會有學習成果浪廢的顧慮。

如果,你對於 Python 的教育推廣議題有興趣,歡迎參加「全國中小學校園自由軟體應用諮詢中心」的通信論壇區 [註4],這個通信論壇是由軟體自由協會(Software Liberty Association of Taiwan, SLAT) 在教育部的補助下所建置,目前已有包括 Python、Zope、PHP、MySQL 在內的課程在進行。

哪些人在用 Python ?

若參考 Python 在各大軟體開發單位的實際應用狀況,知名的例子包括有:Yahoo! 網站的 Maps 與 Groups 服務,都使用 Python 來進行開發;Google 網站從創業之初,其工程師就利用 Python 來開發搜尋引擎功能,目前他們公司仍然急需更多 Python 工程師;美國太空總署 (NASA) 利用 Python 來實作下一代新式的 CAD/CAE/PDM 大型應用系統,他們認為 Python 提供的強大功能與彈性,完全能滿足目前的需求。

幾個常見的 Python 應用程式,諸如 mailman 通信論壇、Red Hat Linux 的安裝程式 Anaconda、PyGame遊戲軟體模組群等。除此之外,Python 在各行各業中也被廣泛應用,著名的成功案例,包括生物資訊產業、製藥業、半導體製造業、電影動畫產業、電腦遊戲產業、金融銀行業、太空科學領域等。其他更 多的應用資訊,可以在 Pythonology 網站 [註5] 上看到。

進一步來看,程式語言是軟體開發過程中的底層工具之一,上層的開發環境與框架 (framework) 也常是程式人員關心的議題,以網頁應用軟體開發 (Web Application Development) 這個領域為例,Zope 就是目前多數 Python 程式人員共同參與的開發框架及實作軟體,同時,在歐洲就興起許多靠 Zope 這套開放源碼軟體,所衍生出顧問、訓練、客製化服務的商業模式,知名的例子有 Beehive、Zope Magazine、Ingeniweb、Nuxeo、REFLAB、Zettai.net 等。

類似的服務及商業模式,此刻也在大陸地區興起,潤普科技 (ZopeChina) 就是其中的一例,而且同樣伴隨有 Python 與 Zope 的社群,稱為「中國 Zope 用戶組」(CZUG.org)。相對來看,目前台灣的 Python 與 Zope 開發人員,其凝聚力仍未跨過組成商業公司的門檻,還有待強化程式人員之間的連結。值得一提的是,在學術界倒有展開一些開發及應用實例,諸如中研院資訊所的 ShareTone 專案,是一個以 Zope 為開發平台的協同溝通系統;而長庚大學黃朝錦老師的 LiveZope 專案,則是採用 Knoppix 為基礎的 Zope 應用光碟。上述兩項專案,都在開放源碼軟體競賽中獲獎,具有應用示範的效果。

什麼是 Zope 及 Plone ?

Zope 指的是 Z Object Publishing Environment,它是以 Python 程式語言為基礎的 Web Application Server 框架及實作品,其框架概要如圖?所示。每次我用技術性的方式展示 Zope,效果總是有限,因此這裡想要倒回來介紹。簡單地說,有了 Zope,就可以讓人快速擁有一部「架站機」開發平台,類似的例子有 WebSphere、Enhydra 等,如果你希望馬上有個又炫又貼心的快速架站機,即類似XOOPS 這樣的軟體工具,那麼還可以使用以 Zope 及 CMF (Content Management Framework) 為基礎所強化的 Plone 工具軟體。

圖6 Zope 系統框架概要示意

簡言之,Python 的殺手級應用是 Zope,而 Zope 的殺手級應用是 Plone,從 O'Reilly 在「開放源碼社群送進 COMDEX」競賽中 [註6],Plone 與Zope 的勝出結果來看,目前社群朋友對 Plone 的喜愛與支持正在熱頭中。另外值得一提的是,第一屆 Plone 研討會也在 2003 年十月間舉辦,會場中揭示了許多 Zope及 Plone 的最新發展規劃,包括 Subversion 與 Plone 的結合,以及 XML 使用者介面的搭配。

Plone 是一個整合過的軟體工具,最容易上手的方式,就是下載 Plone 在 Winodws 平台上的安裝程式,如圖7所示,然後過程中「按下一步」即可,如圖8所示。

圖7 Winodws 平台上的 Plone 安裝畫面

圖8 完整安裝 Plone 的選項畫面

Zope 與 Plone 的發展歷史

在 1996 年之際,Zope 的作者 Jim Fulton 受邀擔任 Web CGI 程式設計的講師,原本不大懂什麼是 CGI (Common Gateway Interface) 的他,在不滿意 CGI架構方式下,重新以 Python 語言開發了幾個提供網頁物件出版功能的模組,這些模組分別稱為 Bobo、Document Template、BoboPOS,後來在繼續擴充模組的情況下,Zope 的前身於焉誕生,Jim Fulton 並組成一家 Digital Creations 公司展開 Zope 的開發及商業化路程,現在,Digital Creations 公司已經正式更名為 Zope 公司,宣示 Zope 在商業化市場上更堅定的腳步。

Zope 系統最早是針對新聞媒體界的應用需求所設計,因此除了一般的會員管理 (membership management)、安全機制 (ACL management)、內容物件管理 (content object management)、搜尋引擎與索引 (catalog and indexing) 之外,也很快納入版本管理 (version control management) 以及工作流程管理 (workflow management) 等服務。這些大型入口網站所必備的服務功能,Zope 公司的工程人員,特別以一個稱為 CMF (Content Management Framework) 的開放源碼專案獨立開發,由於 CMF 擁有良好的擴充及延伸彈性,引發更多奠基在 CMF 之上的改善計畫,Plone 就是這類專案計畫中的佼佼者。

CMF 是一個在 Zope 開發環境之上的入口網站服務架框,由於它的開發焦點是在基礎服務模組的研發與測試,長久以來都有不夠穩定,介面不夠美觀、易用度不高的缺點,Plone 專案計畫的主持人 - Alan Runyan 與 Alexander Limi,便接手解決上述的問題,沒想到這樣的改善構想,迅速吸引廣大開發者的認同與參與,Zope 與 CMF 便退居 Plone 這顆閃亮巨星幕後了。

中文支援狀況及其他

提 Zope 及 CMF 的同時,真的得好好介紹 Plone 一番,因為我們所關心的「中文化議題」,Plone 開發團隊照顧得相當貼心,這也是 Plone 在歐洲地區廣受歡迎的主因之一。

Plone 與 Zope 都是以 Python 語言為基礎所開發,因此 Python 本身的多國語文支援能力,也就變成「天生限制」了。新版的 Python 早已經支援 Unicode 內碼,加上我們也下載得到 Chinese codedec 檔案,Python 底層的內碼轉換工作大抵沒問題,且讓我們觀察一段 Python 的測試,以瞭解其基本的運作原理,如列表5所示。值得一提的是,「許功蓋」問題要注意到反斜線。

大陸地區的社群朋友貢獻了 ChinaPack 及 CJK Splitter 工具,用以協助處理Zope 系統裡的中文斷字斷詞問題。最後,再搭配 Page Template 的 I18N 支援,Plone 使用者只要利用合適的本地化模組 (localizer),就可以輕鬆地擁有多國語文版本的入口網站系統。簡單地說,因前人的努力,後人就可以乘涼,這也是開放源碼開發模式的優勢所在。有 興趣參加 Plone 的多國語文工作小組 (I18N Team) 的朋友,別忘了到 http://plone.org/development/teams/i18n/ 網址找尋更多資訊。

另外,如果有朋友想知道 Python 及 Zope 開發環境下,是否具有不錯的整合開發工具 (IDE tool),在此優先推薦 WingIDE 這套軟體,但它並不是開放源碼軟體,其操作介面如圖9所示。

列表 5 Unicode 物件的指定及操作方式

>>> big5str = 這是 Big5 中文字串
>>> ucsstr = unicode(big5str, big5-2003)
>>> ucsstr
u'\u9019\u662f Big5 \u4e2d\u6587\u5b57\u4e32'
>>> print ucsstr.encode(utf-8)
\xe9\x80\x99\xe6\x98\xaf Big5
\xe4\xb8\xad\xe6\x96\x87\xe5\xad\x97\xe4\xb8\xb2

>>> print ucsstr.encode(big5-2003)
這是 Big5 中文字串

圖9 WingIDE 執行偵錯模式的畫面

後記

在本文中,我刻意讓內容摻雜技術與人文的元素成份,因為,我相信「科技始終來自於人性」,電腦網路只是人們進行溝通與創作的工具,程式語言是人類與 機器的溝通型式,軟體是人們模擬現實世界的創作成果。謹將本文獻給我的父母,當我還是個國三學生時,很幸運地家裡就有一台宏碁 PC,是它讓我開啟通往電腦世界的窗。

這篇文章是一系列 Python 與 Zope 介紹的開端,希望你會喜歡它,下期我們將進一步介紹如何以 Plone 工具軟體,快速建置入口網站系統,並進行客製化。

Python 之發展延革

  • 一九九一年由 Guido van Rossum 於阿姆斯特丹大學創作及發展。
  • 二○○○年至二○○三年七月間,Python 語言由 Zope 公司支援的 PythonLabs 所維護開發,開發團隊的領導人仍為 Guido,但目前他已離開 Zope 公司。
  • 早期 Python 以 C 語言為基底撰寫而成。
  • 以 Java 語言為基底的 Python 語言實作 - Jython 正在發展,並整合 Microsoft .NET 架構。

學習 Python 的網頁資源

如果你是 Python 初學者,可以從下列的 Python 學習資源列表挑選幾篇來閱讀,這些資源都可在網路上免費取得:

  • Python 簡介 -- Python.org 網站上的教學列表。 http://www.python.org/doc/Intros.html
  • Python 教學手冊 -- Guido van Rossum 所撰寫的 Python 教學手冊。 http://www.python.org/doc/tut/
  • 編程學習手冊 -- Alan Gauld 所撰寫的編程教學手冊,除了強調 Python 語言之外,也包含其他程式語言。 http://www.freenetpages.co.uk/hp/alan.gauld/
  • 電腦科學家是這樣想的 (Python 版本) -- http://www.ibiblio.org/obp/thinkCSpy/
  • 深入學習 Python -- 針對有經驗程式人員的免費教學手冊。 http://diveintopython.org/

學習 Python 的四本好書

坊間已出現越來越多 Python 書籍,不過,中文版本的還不算多,有賴更多社群好手投入。

  • The Quick Python Book -- by Daryl D. Harms, Kenneth McDonald, Manning Publications Company 2000
  • Practical Python -- by Magnus Lie Hetland, Apress 2002
  • Text Processing in Python -- by David Mertz, Addison Wesley 2003

Python 的特色

    和其他知名的手稿語言 (script language) 相比,Python 具有下列特色:

  • 物件導向式 (Object Oriented)
  • 直譯式、交談式 (Interpreted, Interactive)
  • 跨平台 (Cross Platform)
  • 容易安裝 (Easy Installing)
  • 易學易用 (Easy Learning)
  • 語法結構清晰 (Clear Syntax and Structure)
  • 延伸與內嵌 (Extended and Embedded)
  • 開放源碼 (Open Source)

說明 網址

Python 資源列表

  • Python 主網站 http://www.python.org/
  • wxPython http://www.wxpython.org/
  • PyGTK: GTK+ for Python http://www.pygtk.org/
  • PyQt http://www.riverbankcomputing.co.uk/pyqt/
  • Vaults of Parnassus: Python Resources http://www.vex.net/parnassus/
  • PyGame http://www.pygame.org/
  • 葉平老師的 PythonCourse Wiki http://wiki.scicos.net/PythonCourse

Zope 資源列表

  • Zope.org http://www.zope.org/
  • Zope Magazine http://www.zopemag.com/
  • Content Management Framework http://cmf.zope.org/
  • Plone http://www.plone.org/
  • 全國中小學校園自由軟體應用諮詢中心 http://www.ossacc.org/
  • ShareTone Project http://www.sharetone.org/
  • LiveZope Project http://zope.org/Members/cchuang/LiveZope-0.1.2_released
  • Zope China http://www.zopechina.com/
  • Zope Newbies http://www.zopenewbies.net/
  • ZopeLabs http://www.zopelabs.com/
  • Zettai.net http://www.zettai.net/
  • WingIDE http://www.wingide.com/
  • Beehive http://www.beehive-eu.com/
  • tcchou http://blog.tcchou.org/
註1: Zope 3 UI Sprint
http://www.zope-europe.org/sl2003/uisprint

註2: Python 授權條款的細節
http://www.python.org/psf/license.html


註3: Python 於教育領域之推廣應用
http://www.python.org/sigs/edu-sig/


註4: 全國中小學校園自由軟體應用諮詢中心 PyZope 通信論壇
http://list.ossacc.org/mailman/listinfo/ossacc-pyzope


註5: 在 Pythonology 網站上整理有成功案例
http://www.pythonology.com/success


註6: O'Reilly 的 "Open Source Goes to COMDEX" 投票競賽結果
http://www.oreillynet.com/contest/comdex/


作者簡介

胡崇偉,現職是中研院資訊所研究助理。專長是技術文件撰寫、Linux 系統整合、數位學習系統,興趣是英式搖滾、認知心理學、佛學、開放源碼,想要到北歐旅行。電子郵件:marr @iis.sinica.edu.tw。

Making a simple web server in Python

Making a simple web server in Python.

written by Jon Berg

The great thing about Python is what they call "batteries included", that means a lot of functionallity is bundled with the programming language. And the functionallity is fairly straight to use.

Today we are going to demonstrate how to build a web server in less than 30 min. using the classes from the Python library. We are also going to have some "advanced" functionallity in this server. We want to do dynamic content serving (ala what ASP or PHP do), and be able to take POST from forms. This may sound as a complex task, but as you will see every body can acomplish this through some high level programming interfaces. You don't have to know much about the HTTP protocol at all. Except some basic that when the client request something it is a "GET", and when the client sends something it is in our case a POST. Some basic responce codes like 200 is OK for GET, and 404 is file not found, 301 is OK for a Post.

The web server is implemented as an extention of the BaseHTTPRequestHandler. This means that we define a class an implemenet some methods that will be called when the web server gets requests. There are two methods one for GET requests and one for POST requests.

Lets look at the code:


The main() tries to start the server at port 80 with a reference to the class we just implemented. To quit the server you can press ctrl-c. And the server will close the socket and quit.

The do_GET() gets invoked when you do a GET request. It do checking to see what type of file is requested. If it is a html file it tries to open it and send it to the client. If it is a esp file, our dynamic content, it will print out the current day and year.

The do_POST() gets invoked when you do a POST request. It then displays the content that is uploaded. The name of the formelement is hardcoded to be "upfile".

Running the example:
start the webserver with python webserver.py
Then you can open your web browser and type in http://localhost/index.html or http://localhost/index.esp
To test the upload, you open the upload.html, press browse, open a small text file, click "press", the server will echo back the file.

Download the example code. (webserver.py, index.html, upload.html)


Pointers to related stuff on the hypertext transfer protocol (http) and web servers:

Making a simple web server in Java. (a bit lower level) This is a tutorial I did on how to do somewhat the same but in Java. This implementation is much more bottom up, with sockets and not that many short cuts as you can do in Python.

HowStuffWorks This is a very basic introduction for the novice on how web servers works. Has also other text about Internet and Routers, in easy to understandable language. Nice if you are starting out learning.

HTTP Made Really Easy Here is some nice text that goes through the main points in HTTP. A little more technical. It's recommended that you know these things to understand the above tutorial.

Apache the best and most widely used web server on the Internet today, check it out. If you want to run your own web server this is the one to get, you can get binaries for both Windows and Unix. You can download the entire sourcecode if you want to check how it was made.

Mozilla / Netscape is a nice web browser. Get rid of the Explorer.

RFC-1945 RFC describing Hypertext Transfer Protocol -- HTTP/1.0

RFC-2616 RFC describing Hypertext Transfer Protocol -- HTTP/1.1

RFC webpage The Request For Comment webpage, RFC are technical documents describing all sorts of protocols on the Internet.

Python webpage Download Python for windows or linux.



Google
Let Google Handle Email for your Domain Name
Page Rank banned by Google
Google's highest ranked web pages
SEO intelligent spam causes irrelevant search results
Google Sandbox
Google ranking factors
How to not give out page rank in web page links

Web Server Programming
Simple Java web server
Simple Python web server
Configuring Apache webserver with .htaccess file

Windows
Turn off the loginscreen in XP, after installing .NET .

Turn off xp login screen unread mail count
What is .NET

Web (webmastering)
Introduction to Cascading style sheets (CSS)
The value of Alexa traffic rank
HTML META tag, not a search engine optimization tool
Create a maintainable webpage with modularization
The www prefix in your domain name
What is RSS and cool things RSS can be used for
MySql backup and restore with phpMyAdmin

Mix Computer related text
Doing business (making money) with Information Technology
Business with Computer Science
Research in Computer Science
Current and future possibilities of Medical Informatics
Tasks that make sense to have automated
Programming handheld mobile devices (overview)
Security tips for the web surfer
Price and Capacity in computer hardware
Java RMI Tutorial.

Microsoft Word
Page numbering in Word
Numbering headers or outlines in Word
Create a List of Figures
Turn off the default collapsing menus in Word

PHP vs. Python

> I think he means, "scale to larger programs," not "scale to more
> processors."

Yes. I will try to be more specific. There is several reasons why Python
scales better than PHP.

(1) Python uses namespaces, PHP - not. The bigger programm the bigger
probability of conflict among names in PHP.

(2) Not only PHP lacks namespaces. It has one big inconsistent mess with
its function naming! Inconsistent prefixes, order of parameters. Mess. It
is difficult to memorize it. Python programming need less interupting for
reading manual.

(3) Python uses modules, PHP - not. Python can download single or some
classes from many big modules (eg. from module1 import class1, var1, fun1).
PHP is primitive in its copy-paste *all* included files! So Python uses
less memory than PHP and do not need to parse so many lines.

(4) Python automatic compile every imported modules into bytecode, PHP has
to parse all those mess. Without accelerators PHP is much slower for bigger
applications. This is the reason why PEAR is so slow. This is the reason
why ezPublish is so slow. The bigger code (more included files), the slower
PHP works.

(5) Python compile its modules automatic and do not need to parse them for
every browser request like PHP do.

(6) Pythonic application server (eg. Webware) do not need to load and parse
any files from filesystem at all! It loads them once, compile it and store
compiled scripts in memory. PHP has to load files from filesystem, parse
them and execute. From my own experience: when I moved from PHP to Webware
and I compared its performance with (similar scale) php appplications, my
webware was almost 6 times faster!

(7) Python has much better free IDE editors with graphic debugger inside.
PythonWin, Boa, SPE, Eric3 etc. It is much easier debug in Python than i
PHP for larger programmes.

(8) And last but not least. Python is truly object oriented, general
purpose language. PHP is not general purpose language. PHP4 has very poor
OO. (PHP5 has better, but has also some useless new features like private
variables. They have sense for static compiled languages like C++ or Java ,
not for dynamic ones.) Python also uses sofisticated exception handling,
uses namespaces, has module import, has better unicode support, has more
consistent api etc.
One more example from my experience. I always have problem with converting
string among iso-8859-2, cp1250, mac-ce and utf-8. PHP utf8 functions are
poor, implements useless (for me) iso-8859-1 only. iconv library for PHP is
even worse, when it cannot convert some characters it deletes the following
characters! PHP has no such like: unicode(txt, 'cp1250').encode('cp1250',
'xmlcharrefreplace'). When some characters exists only in cp1250 but not in
iso-8859-2 that function convert them into xml entity &#number; Cute!

Wednesday, October 29, 2008

Python vs. PHP

Python vs. PHP

Introduction

Every month or so someone posts to comp.lang.python asking how Python compares to PHP. Python's 'language comparisons' page doesn't have an entry for PHP so here's a first draft. This work-in-progress compares PHP and Python and evaluates their relative strengths for web development.

Please contribute! Once there's some flesh on this skeleton, I'll tidy it up and submit it to: http://python.org/doc/Comparisons.html

-- TavisRudd? - 23 Nov 2001 -- MikeOrr - 15 Dec 2001 -- DiogoResende - 21 Jun 2007 :) -- SamuelCochran - 6 Jan 2008

Common Ground

Both PHP and Python:

  • are interpreted, high level languages with dynamic typing
  • are OpenSource (except PHP's ZEND engine?)
  • are supported by large developer communities
  • are easy to learn (compared to Java, and even Perl)
  • are easy to extend in C, C++ and Java
  • are extremely portable. They run on almost all platforms in existence without recompilation.
  • support for variable number of function arguments.
  • have the ability to freeze live objects in a string representation (for storing arbitrary objects on disk, moving them over the network, etc); they can then be converted back to identical objects with data intact. PHP's serialize function; Python's pickle and marshal modules. Note that PHP, handling of serialized objects and classes is much weakier and error prone than Python's due to PHP's lack of modules. When an object is serialized, only its attributes are stored, not its methods. Thus, the object's class must be present (with the exact same name) in the script that unserializes it. In Python this is handled automatically via the module/import framework. (this COULD be handled with PHP 5's __autoload(), but is not done automatically)

Compared as Languages

What does PHP have that Python doesn't?

  • syntax from C and Perl, with lots curly braces and dollar signs
  • the 'switch' statement and 'do ... while' construct
  • increment and decrement and assignment operators (assignment is a statement only in Python)
  • the ternary operator/statement (... ? ... : ...) (Python 2.5 added x = value if test() else other_value)
  • schizophrenic tableau of function names. The builtin library has a wide variety of naming conventions. There are no namespaces, so functions often have prefixes to denote their source (but often not). Functions are often placed into classes to simulate namespaces.
  • a very casual language, where globals are often used to pass arguments, all variables are "set" (to NULL), and a somewhat weak type system (not to be confused with dynamic types) (global variables should not be used, that is language independent)
  • an expedient (commonly installed) environment
  • aliases ('$a =& $b' means that when $b changes, $a changes also) (should be "references", not "aliases", but are called aliases)
  • one array type that doubles as a list and a dictionary. Dictionary keys are iterated in their original order.
  • (An EXCELLENT on-line Manual)
  • (Class magic methods)
  • (A somewhat clean code. Where is the public/private/protected/final/.. atributes in python? Why do I have to always put "self" on class methods?)

What does Python have that PHP doesn't?

  • a general purpose programming language (not just for the web) (not true PHP has a CLI SAPI, and is embeddable) (PHP was created for the web but has branched into general purpose applications, however it's arguably not "good at/for it")
  • indentation is used to mark out block structure rather than curly braces
  • namespaces and modules
  • a small core
  • very clear, concise, and orthogonal syntax
  • it is self documenting with docstrings and pydoc (PHP 5 has reflection and doc strings)
  • keyword arguments to functions and methods, easy support for default arguments (PHP has easy support default arguments: http://uk2.php.net/manual/en/functions.arguments.php)
  • true object orientation and 'first class' classes and functions (OO has been completely revamped in PHP 5)
  • classes are used extensively in the standard library
  • a notion of private attributes (PHP 5 supports this)
  • multiple inheritance
  • object-oriented file handling
  • method chaining
  • excellent introspection (PHP 5 Reflection)
  • everything is a reference! (references are painful in PHP) (Not in PHP 5)
  • one 'del' statement for all data types. PHP has 'unset' for variables and something else for array members. (Array members can be unset())
  • consistent case sensitivity (PHP does for variables, but not functions) (Functions are case insensitive)
  • a simple array slicing syntax
  • lambdas and other builtin functional programming constructs (php.net/create_function - create_function is not a true lambda and pollutes the global namespace, particularly dangerous in any type of loop)
  • iterators (PHP 5)
  • structured exception handling (PHP 5)
  • operator overloading
  • SWIG? integration
  • threading
  • an excellent profiler, plus several debuggers and IDEs (PHP has had this for a long time)
  • lots of high-level data types (lists, tuples, dicts, mx.DateTimes, NumPy arrays, etc.)
  • differentiation between arrays (lists) and associative arrays (dictionaries) (that is not an advantage)
  • dates that aren't limited to UNIX timestamps (<1970,>2038)
  • cached byte-code compilation (available for $980 in PHP!) (pecl.php.net/apc -- FREE, but not standard amongst PHP hosts) (roadsend is now also open source)
  • a standardized database API (pecl.php.net/PDO -- PHP 5.1)
  • support for all major GUI frameworks
  • strong internationalization and UNICODE support (May be available in PHP 6, but only when enabled and requires an external package)
  • maturity, stability and upward-compatibility (PHP is stable, mature and up/backward-compatible - not cleanly?)
  • tends to lead to much more scalable applications -- importing modules is safer than textually including code as in PHP: global variables are not used to exchange information. (global variables should not be used, that is language independent)

Compared as Web Development Frameworks

Unlike PHP, which has web development features built directly into the core language, Python's web development capabilites are provided by add-on modules. Basic CGI capabilities are provided by the 'cgi' module which comes in Python's standard library. There's also a wide range of third-party modules available for Python; some are complementary, others compete. As a result, Python provides a more flexible base for web development.

There are some adverse side effects of this flexibility. First, the range of choices can be bewildering. Unless you are working experienced Python web developers, PHP is easier to get started with. Second, support for PHP is more common with shared-hosting companies than support for the various Python options.

Another difference is that PHP is embedded in the web server, whereas Python web applications can either be embedded in the web server like PHP or run in a separate process. Here's a simple classification of Python web development platforms:

  • emdedded in the web server process
    • Apache modules mod_python and mod_snake embed the Python interpreter in Apache and allow other Apache modules to be written with Python. This is the same idea as mod_perl.
    • PyWX is an extension to AOLServer that serves the same purpose as the Apache modules above.
    • MS ASP scripts can be written using Python via Active Scripting Host.
  • running in a separate process
    • non-persistent process (a new process is spawned for each request)
      • custom CGI scripts
    • persistent process (all requests are sent from the web server to one persistent process, sometimes via a CGI wrapper)
      • custom Fast-CGI scripts
      • custom SCGI scripts
      • custom WSGI? modules
      • 'Application Servers'
        • Zope -- comes with its own web server but can also communicate with Apache via the CGI or Fast-CGI protocols.
        • Webware? -- works with any web server via CGI. With Apache it can communicate via a custom Fast-CGI like protocol.
        • SkunkWeb? -- only works with Apache, communicates via a custom Fast-CGI like protocol.

(Note: PHP programs can be run standalone or as ordinary CGI scripts. However, when called indirectly from the web (e.g., from a Perl CGI script), it requires unsetting an undocumented number of web environment variables so that PHP doesn't think it's running from the web and look in the wrong place for the script. Likewise, it's _possible_ to write a long-running server in PHP, but there are precious few examples of it.)

The vast majority of Python web applications are run in a separate process. This has some important implications. ... to be continued ...

... please add your observations

Python Template Engines

...

Here's some interesting notes on security in PHP: (Not true. The tutorial assumes default conf values that are not default anymore or don't even exist) http://www.securereality.com.au/studyinscarlet.txt

Community Support

PHP

  • huge installed user base, but the figures are probably distorted by shared hosting (Not true. It has PEAR and PECL repository)
  • low signal-to-noise ratio -- because PHP is so expedient, many of the users are not invested in the technology (or even their own code) or the community (Not true. IBM and Oracle invested in PHP)

Python

  • sizable, but not huge, installed user base
  • Python Software Foundation
  • lots of specialized interest groups
  • very high signal-to-noise ratio

Documentation

Core Documentation

Although both PHP and Python have excellent core documentation, Python's is more extensive and generally higher quality. PHP has a large number of translations available. Python doesn't. For PHP see http://www.php.net/docs.php and for Python see http://python.org/doc/ Python allows documentation on modules, classes, and functions to be included in the program code. The documentation becomes an attribute of the module/class/function, accessible from inside of the language itself. (This is so untrue. Python docs are short and don't explain in detail how something can or should be used. PHP uses examples (L.B.E.). PHP has comments on every page so you can check for someone that tried to do the same thing you did. PHP can be documented just like many other languages like C for example; http://www.phpdoc.org/ )

Frequently Asked Questions

Q1

... what is the best way to build web-based database applications like accounting systems, on Python? i.e. what is the equivalent of ASP pages or PHP pages or JSP pages, for Python?? Shouldn't we be learning THAT instead of PHP???

A1

There is no simple answer to this question. There are many tools available for doing this in Python. So many that the choices can be bewildering. You're best to think of the tools as falling into two complementary categories: Application Servers (there's probably a better term to use here) and Template Engines.

Application Servers:

Templating Engines:

My personal preference is Apache/Webware/Cheetah. I'll write more about this later. -- TavisRudd? - 23 Nov 2001

General Discussion

(add your comments here, along with a signature and date)


I haven't used PHP with XML, and I've only used Python with XML a little, but I get the impression Python is much better suited -- specifically because it is strongly types, where PHP is rather weak in its typing (like C). But I can't say from experience

-- IanBicking - 26 Nov 2001


To clarify, PHP's types are more dynamic than Python's. All variables are automatically initialized to NULL. It automatically converts between strings, numbers and NULL when a different type is needed for the operation, or with a type case. It also "does something" to convert to/from array and object. '123' -> 123, 'non-numeric' -> 0, NULL -> '', etc. Sometimes all this is convenient, especially when a missing CGI param converts to NULL which converts to '' in the VALUE= attribute, but it also leads to wrong ouput rather than errors if you misspell a variable or key.

PHP does not have first-class functions. There are equivalents to Python's map, reduce, filter, and there's array_walk, but they all take the name of a function rather than the function itself.

Examples of PHP's schizophrenic function naming: (string functions) stripslashes vs strip_tags; (array functions) array_keys vs asort vs count and shuffle; (variable functions etc) isset vs is_array.

PHP has constants, which are initialized with a totally different syntax than variable assignment. The advantage of constants is that they can be defined only once, allowing you to define sensitive constants in a secure include file, then prevent untrusted code from overriding them. Constants are global: they bypass the scoping rules. One disadvantage is that a constant is a bare word: if you misspell it, you'll silently get a NULL value.

Syntax errors show the file and line number, but not the character position. Sometimes the error message is specific, sometimes just "parse error". This leads to staring at the code for a while until you realize you're missing '$' or ';', or you put something besides a semicolon on the END line matching <<

-- MikeOrr - 15 Dec 2001