始めよう
Pythonの長所
- オブジェクト指向 (OOP)
like ... Smalltalk, C++, Java
- オープン・ソース
フリーだけじゃなく,開発に参加できる
- 移植性
- 強力
- 複合言語化可能
C, C++ で書いた部品と結合できる
- 使いやすい
インタプリタ・スクリプト言語
中間言語(バイトコード)
Pythonの用途
- システム・ユーティリティ
- GUI
- プロトタイピング
- インターネット・スクリプト (CGI)
- 数値計算
- データベース
Pythonと類似ツール
Python プログラムの実行
パスの設定
他のアプリケーションでも一緒だが,コマンドがインストールしてあっても
パスが通っていないと使えない.
% which python
no python in /usr/bin /bin /usr/openwin/bin
% set path = (/pub/solaris/python/bin $path)
% which python
/pub/solaris/python/bin/python
% python
[GCC 2.8.1] on sunos5
Type "copyright", "credits" or "license" for more information.
>>>
対話的に(インタラクティブ)
% python
>>> print 'Hello world!'
Hello world!
>>> 35 + 65
100
>>> x = 35
>>> y = 65
>>> print x + y
100
>>> (Ctrl+D) or (Ctrl+Z) 終了
モジュールファイルの実行
% cat > spam.py
import sys
print sys.argv
(Ctrl+D)
または,テキストエディタやviなどで作成してもよい.
% python spam.py -i eggs -o bacon
['spam.py', '-i', 'eggs', '-o', 'bacon']
スクリプトの作成と実行
- 最初の行が特殊(なコメント)
#! で始まる
- 実行可能パーミッション
chmod +x ...
% cat > brian
#!/pub/solaris/python/bin/python
print 'The Bright Side of Life ...'
(Ctrl+D)
または,テキストエディタやviなどで作成してもよい.
% chmod +x brian
% brian
The Bright Side of Life ...
Python は 行の中に # が現れると,そこより後をコメントとみなすので,
python brian でも同じように実行できる.
また,最初の行は #!/usr/bin/env python でもよい.
モジュールファイルについて
モジュールは import できる.
% cat > myfile.py
title = "The Meaning of Life"
(Ctrl+D)
または,テキストエディタやviなどで作成してもよい.
% python
>>> import myfile
>>> print myfile.title
The Meaning of Life
あるいは,
% python
>>> from myfile import title
>>> print title
The Meaning of Life
名前空間
dir 関数
Python の環境設定
Cシェルの path 変数を設定.(または 環境変数 PATH を設定)
~/.cshrc に path を設定しているところがあるので,/pub/solaris/python/bin を
付け加えておこう.
システムによっては教科書のような setenv が必要かもしれない.
GUIテスト
% python
>>> from Tkinter import *
>>> w = Button(text='Hello', command='exit')
>>> w.pack()
>>> w.mainloop()
練習問題
- 対話的に Python コマンドを実行してみよう.適当な文字列の print と,
単純な計算,変数を使った計算の print を試してみよう.
- テキストエディタを用いて,上で試したことを行なう,簡単なモジュール
ファイルを作成しなさい.このファイルをシェルのコマンドラインから
python の引数として与えて実行してみなさい.
- Python を対話的に起動し上のモジュールを import しなさい.
- 作成したモジュールの最初の行に #! で始まる行を入れ,ファイルの
実行権を付けることによって,シェルのコマンドラインから直接
スクリプトファイルを呼び出して実行しなさい.
- 1 / 0 を実行すると,どうなるだろうか?