Archive for the ‘Python’ Category
-
Hello, Tkinter World!
Posted on 5月 15th, 2013 by cx20
Tkinter
Tkinter は Tcl スクリプト用の GUI ツールキット「Tk」を Python から呼出し可能にしたライブラリである。
以下は Python による Tkinter の呼出し例となっている。ソースコード
from Tkinter import * window = Tk() window.title( 'Hello, World!' ) window.geometry( '640x480' ) label = Label( text = "Hello, Tkinter World!" ) label.pack( side = 'top', anchor = 'w' ) window.mainloop()
実行方法
C:¥> python hello.py
実行結果
+------------------------------------------+ |Hello, World! [_][~][X]| +------------------------------------------+ |Hello, Tkinter World! | | | | | | | | | | | | | | | | | | | +------------------------------------------+
-
Hello, ODBC(Python) World!
Posted on 9月 26th, 2012 by cx20
DB API
ODBC(Open Database Connectivity)は、マイクロソフト社が提唱した DBMS 接続用の API 仕様である。
DBMS の差異は ODBC ドライバによって吸収される為、ODBC の手順にしたがってプログラムを作成すれば、基本的な差異を意識せず、プログラムすることができる。ODBCドライバ ファイル Microsoft Access Driver (*.mdb) ODBCJT32.DLL Microsoft Text Driver (*.txt; *.csv) ODBCJT32.DLL Microsoft Excel Driver (*.xls) ODBCJT32.DLL Microsoft dBase Driver (*.dbf) ODBCJT32.DLL Microsoft ODBC for Oracle MSORCL32.DLL Microsoft Paradox Driver (*.db ) ODBCJT32.DLL SQL Server SQLSRV32.DLL Microsoft Access Driver (*.mdb, *.accdb) ACEODBC.DLL SQL Server Native Client 10.0 SQLNCLI10.DLL Python DB API は Python 向けの Database Interface(API)である。
ODBC ドライバを介することで、様々な DBMS への接続が可能となっている。ソースコード(Python + DB API + ODBC + SQL Server)
import pyodbc cn = pyodbc.connect("DRIVER={SQL Server};SERVER=(local);DATABASE=master;UID=sa;PWD=P@ssW0rd") cur = cn.cursor() cur.execute("SELECT 'Hello, ODBC World!' AS Message") rows = cur.fetchall() for row in rows: print "Message" print "-------------------" print row[0] cur.close() cn.close()
実行方法(Windows)
C:¥> python hello.py
実行結果
Message ----------------- Hello, ODBC World!
-
Hello, ADO(Python) World!
Posted on 9月 25th, 2012 by cx20
ADO(Python)
ADO(ActiveX Data Objects)は、マイクロソフト社が開発した COM ベースの DBMS 接続用 API である。
OLE DB プロバイダを介することで様々な DBMS への接続が可能となっている。
OLE DB プロバイダとしては、以下のようなプロバイダがある。いくつかが OS 標準で付属している他、追加インストールが可能である。プロバイダ名 表示名 説明 MSDASQL Microsoft OLE DB Provider for ODBC ODBC データベース Microsoft.Jet.OLEDB.4.0 Microsoft OLE DB Provider for Microsoft Jet Microsoft Jet データベース Microsoft.ACE.OLEDB.12.0 Microsoft Office 12.0 Access Database Engine OLE DB Provider Microsoft Access データベース SQLOLEDB Microsoft OLE DB Provider for SQL Server Microsoft SQL Server SQLNCLI10 SQL Server Native Client 10.0 Microsoft SQL Server MSDAORA Microsoft OLE DB Provider for Oracle Oracle データベース 以下は Python による ADO ライブラリの使用例となっている。
ソースコード(Python + ADO + OLEDB + Jet データベース)
import win32com.client cn = win32com.client.Dispatch('ADODB.Connection') cn.Open( "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=.hello.mdb" ) rs = cn.Execute( "SELECT 'Hello, ADO World!' AS Message" )[0] while not rs.EOF: print rs.Fields(0).Name print "-------------------" print rs.Fields(0).Value rs.MoveNext() rs.Close() cn.Close()
ソースコード(Python + ADO + OLEDB + ACE データベース)
import win32com.client cn = win32com.client.Dispatch('ADODB.Connection') cn.Open( "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=.hello.accdb" ) rs = cn.Execute( "SELECT 'Hello, ADO World!' AS Message" )[0] while not rs.EOF: print rs.Fields(0).Name print "-------------------" print rs.Fields(0).Value rs.MoveNext() rs.Close() cn.Close()
ソースコード(Python + ADO + OLEDB + SQL Server)
import win32com.client cn = win32com.client.Dispatch('ADODB.Connection') cn.Open( "Provider=SQLOLEDB;SERVER=(local);DATABASE=master", "sa", "P@ssW0rd" ) rs = cn.Execute( "SELECT 'Hello, ADO World!' AS Message" )[0] while not rs.EOF: print rs.Fields(0).Name print "-------------------" print rs.Fields(0).Value rs.MoveNext() rs.Close() cn.Close()
ソースコード(Python + ADO + OLEDB + Oracle)
import win32com.client cn = win32com.client.Dispatch('ADODB.Connection') cn.Open( "Provider=MSDAORA;Data Source=ORCL", "scott", "tiger" ) rs = cn.Execute( "SELECT 'Hello, ADO World!' AS Message FROM DUAL" )[0] while not rs.EOF: print rs.Fields(0).Name print "-------------------" print rs.Fields(0).Value rs.MoveNext() rs.Close() cn.Close()
実行方法(Windows)
C:¥> python hello.py
実行結果
Message ----------------- Hello, ADO World!
-
Hello, DB API(Python) World!
Posted on 9月 24th, 2012 by cx20
DB API
Python DB API は Python 向けの Database Interface(API)である。
各データベースドライバを介することで、様々な DBMS への接続が可能となっている。ソースコード(Python + DB API + MySQL)
import MySQLdb cn = MySQLdb.connect(db="test", host="127.0.0.1", port=3306, user="root", passwd="P@ssW0rd") cur = cn.cursor() cur.execute("SELECT 'Hello, DB API World!' AS Message") rows = cur.fetchall() for row in rows: print "Message" print "-------------------" print row[0] cur.close() cn.close()
実行方法(Windows)
C:¥> python hello.py
実行結果
Message ----------------- Hello, DB API World!
-
Hello, Win32 GUI(Python) World!
Posted on 7月 15th, 2012 by cx20
Win32 GUI(Python)
Win32 アプリケーションは Windows 標準 API である Win32 API を使用した Windows アプリケーションである。
以下は Python にて ctypes ライブラリを使用した Win32 GUI アプリケーション の例となっている。ソースコード
import win32con import sys from ctypes import * WNDPROC = WINFUNCTYPE(c_long, c_int, c_uint, c_int, c_int) NULL = c_int(0) WM_PAINT = win32con.WM_PAINT WM_DESTROY = win32con.WM_DESTROY CS_HREDRAW = win32con.CS_HREDRAW CS_VREDRAW = win32con.CS_VREDRAW IDI_APPLICATION = win32con.IDI_APPLICATION IDC_ARROW = win32con.IDC_ARROW WHITE_BRUSH = win32con.WHITE_BRUSH WS_OVERLAPPEDWINDOW = win32con.WS_OVERLAPPEDWINDOW CW_USEDEFAULT = win32con.CW_USEDEFAULT SW_SHOWNORMAL = win32con.SW_SHOWNORMAL SW_SHOW = win32con.SW_SHOW SW_SHOWDEFAULT = win32con.SW_SHOWDEFAULT GetModuleHandle = windll.kernel32.GetModuleHandleA BeginPaint = windll.user32.BeginPaint EndPaint = windll.user32.EndPaint PostQuitMessage = windll.user32.PostQuitMessage DefWindowProc = windll.user32.DefWindowProcA CreateWindowEx = windll.user32.CreateWindowExA CreateWindowEx.argtypes = [c_int, c_char_p, c_char_p, c_int, c_int, c_int, c_int, c_int, c_int, c_int, c_int, c_int] LoadIcon = windll.user32.LoadIconA LoadCursor = windll.user32.LoadCursorA RegisterClass = windll.user32.RegisterClassA ShowWindow = windll.user32.ShowWindow UpdateWindow = windll.user32.UpdateWindow GetMessage = windll.user32.GetMessageA TranslateMessage = windll.user32.TranslateMessage DispatchMessage = windll.user32.DispatchMessageA TextOut = windll.gdi32.TextOutA GetStockObject = windll.gdi32.GetStockObject class POINT(Structure): _fields_ = [('x', c_long), ('y', c_long)] class MSG(Structure): _fields_ = [('hwnd', c_int), ('message', c_uint), ('wParam', c_int), ('lParam', c_int), ('time', c_int), ('pt', POINT)] class WNDCLASS(Structure): _fields_ = [('style', c_uint), ('lpfnWndProc', WNDPROC), ('cbClsExtra', c_int), ('cbWndExtra', c_int), ('hInstance', c_int), ('hIcon', c_int), ('hCursor', c_int), ('hbrBackground', c_int), ('lpszMenuName', c_char_p), ('lpszClassName', c_char_p)] class RECT(Structure): _fields_ = [('left', c_long), ('top', c_long), ('right', c_long), ('bottom', c_long)] class PAINTSTRUCT(Structure): _fields_ = [('hdc', c_int), ('fErase', c_int), ('rcPaint', RECT), ('fRestore', c_int), ('fIncUpdate', c_int), ('rgbReserved', c_char * 32)] def WndProc(hwnd, message, wParam, lParam): strMessage = "Hello, Win32 GUI(Python) World!" if message == WM_PAINT: ps = PAINTSTRUCT() hdc = BeginPaint( hwnd, byref(ps) ) TextOut( hdc, 0, 0, strMessage, len(strMessage) ) EndPaint( hwnd, byref(ps) ) return 0 elif message == WM_DESTROY: PostQuitMessage(0) return 0 return DefWindowProc(hwnd, message, wParam, lParam) def WinMain(): wndclass = WNDCLASS() wndclass.style = CS_HREDRAW | CS_VREDRAW wndclass.lpfnWndProc = WNDPROC(WndProc) wndclass.cbClsExtra = 0 wndclass.cbWndExtra = 0 wndclass.hInstance = GetModuleHandle(0) wndclass.hIcon = LoadIcon(0, IDI_APPLICATION) wndclass.hCursor = LoadCursor(0, IDC_ARROW) wndclass.hbrBackground = GetStockObject(WHITE_BRUSH) wndclass.lpszMenuName = 0 wndclass.lpszClassName = "helloWindow" RegisterClass(byref(wndclass)) hwnd = CreateWindowEx( 0, wndclass.lpszClassName, "Hello, World!", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, 0, 0, wndclass.hInstance, 0) ShowWindow(hwnd, SW_SHOWDEFAULT) UpdateWindow(hwnd) msg = MSG() pMsg = pointer(msg) while GetMessage( pMsg, NULL, 0, 0 ) != 0: TranslateMessage(pMsg) DispatchMessage(pMsg) return msg.wParam if __name__=='__main__': sys.exit(WinMain())
実行方法
C:¥> python hello.py
実行結果
+------------------------------------------+ |Hello, World! [_][~][X]| +------------------------------------------+ |Hello, Win32 GUI(Python) World! | | | | | | | | | | | | | | | | | | | +------------------------------------------+
-
Hello, COM(Python) World!
Posted on 5月 25th, 2012 by cx20
Python
COM(Component Object Model)はマイクロソフトの提唱するプログラム部品の仕様である。
COM を用いて開発された部品であれば言語を問わず利用することができる。
以下は Python による COM クライアントの例となっている。ソースコード
import win32com.client shell = win32com.client.Dispatch('Shell.Application') folder = shell.BrowseForFolder( 0, "Hello, COM(Python) World!", 0, 36 )
実行方法
C:¥> python hello.py
実行結果
+----------------------------------------+ |Browse For Folder [X]| +----------------------------------------+ | Hello, COM(Python) Wolrd! | | | | +------------------------------------+ | | |[Windows] | | | | +[addins] | | | | +[AppCompat] | | | | +[AppPatch] | | | | +[assembly] | | | | : | | | | : | | | | : | | | +------------------------------------+ | | [Make New Folder] [ OK ] [Cancel] | +----------------------------------------+
-
Hello, Win32 API(Python) World!
Posted on 4月 29th, 2012 by cx20
Win32 API(Python)
Win32 API は、Windows の機能にアクセスする為の API(Application Programming Interface)である。
以下は Python にて ctypes ライブラリを使用した呼出し例である。ソースコード
import ctypes user32 = ctypes.windll.user32 user32.MessageBoxA( 0, "Hello, Win32 API(Python) World!", "Hello, World!", 0 )
実行方法
C:¥> python hello.py
実行結果
--------------------------- Hello, World! --------------------------- Hello, Win32 API(Python) World! --------------------------- OK ---------------------------
-
Hello, Django World!
Posted on 2月 24th, 2012 by cx20
Django
Django は Python で実装された Web アプリケーションフレームワークである。名前の由来は作者の好きなミュージシャンから。
元々はアメリカのある新聞社の社内ツールとして開発された。現在はオープンソースで、Google App Engine でも採用されている。
Django には独自のテンプレートエンジン、O/R マッパー、正規表現を用いた URLディスパッチャーなどの機能が含まれる。
ここでは主要な機能のテンプレートエンジンを使用したサンプルを記載する。
ソースコード(テンプレート)
Content-Type: text/html <html> <head> <title>Hello, World!</title> </head> <body> <p>Hello, {{message}} World!</p> </body> </html>
ソースコード(CGIコード)
#!/usr/bin/env python from django.conf import settings from django.template import Context from django.template.loader import get_template settings.configure(TEMPLATE_DIRS=('/Applications/MAMP/cgi-bin/python',)) tmpl = get_template('template.html') print tmpl.render(Context({'message' : 'Django' }))
実行方法
1. CGI用フォルダ(cgi-bin等)に配置 2. 実行権限の付与 $ chmod +x hello.py 3. ブラウザで表示 http://localhost/cgi-bin/hello.py
実行結果
Hello, Django World!
-
Hello, Cheetah World!
Posted on 2月 23rd, 2012 by cx20
Cheetah
Cheetah は Python 用の汎用テンプレートエンジンである。名前の由来は動物のチータから。
ソースコード(テンプレート)
<html> <head> <title>Hello, World!</title> </head> <body> <p>Hello, $message World!</p> </body> </html>
ソースコード(CGIコード)
#!/usr/bin/env python from Cheetah.Template import Template tpl = Template(file='hello.tpl') tpl.message = 'Cheetah' print "Content-Type: text/htmlnn" print tpl
実行方法
1. CGI用フォルダ(cgi-bin等)に配置 2. 実行権限の付与 $ chmod +x hello.py 3. ブラウザで表示 http://localhost/cgi-bin/hello.py
実行結果
Hello, Cheetah World!
-
Hello, IronPython World!
Posted on 1月 20th, 2012 by cx20
IronPython
IronPython はオブジェクト指向スクリプト言語 Python の .NET 実装である。
Python の構文が使える他、.NET Framework のライブラリが利用できる。
名前の由来は「料理の鉄人(The Battle of Iron Chef)」から。CPython vs IronPython をかけたシャレらしい。
Jython(Python の Java 実装)の作者、Jim Hugunin 氏によって開発された。
C# 同様に、UNIX 環境向けの .NET Framework 互換プロジェクト「Mono」により他の OS でも動作させることができる。
ソースコード
ソースコード(.NET ライブラリを使用した場合)
#!/usr/bin/env ipy from System import * Console.WriteLine("Hello, IronPython World!")
実行方法(スクリプトファイルを指定して実行)
$ ipy hello.py
実行方法(実行権限を付与して実行)
$ chmod +x hello.py $ ./hello.py
実行結果
Hello, IronPython World!