Python - オブジェクト指向スクリプト言語

文字の利用

# 文字変数の宣言
strval="string"
strval='string'

# 文字列の連結
strval = 'str' + 'ring'   # string
strval = 'str' 'ring'     # string

# 文字列の反復
strval  = "string"
strval2 = strval*2     # stringstring

# 文字列の添字表記
strval1[0]      #'T'
strval1[0:2]    #'TE'

数値の利用

# 数値変数の宣言
intval=100

# 整数の除算は floor (実数の解を越えない最大の整数) を返す:
intval = 7/3    ※2

リストの利用

# リスト変数の定義
a = ['str1', "str2", 100, 1234]
a[0]   #str1
a[1]   #str2

# リスト内容の置換
a = ['str1', "str2", 100, 1234]
a[0:2] = [111, 222]  # a = [111,222,100,123]

# リスト数の取得
a = ['str1', "str2", 100, 1234]
len(a)   #4

if文

if x < 0:
    x = 0
    print 'Negative changed to zero'
elif x == 0:
    print 'Zero'
elif x == 1:
    print 'Single'
else:
    print 'More'

for文

# いくつかの文字列の長さを測る:
 list1 = ['cat', 'window', 'defenestrate']
 for x in list1:
     print x, len(x)

pass 文

pass  # なにもしない

関数の利用

# 戻り値のない関数
def hello(x,y):
    print "hello world!"
 
# 戻り値のある関数
def add(x,y):
    return x + y

モジュールの利用

echotest.py

def echo1():
    print "test1!"

def echo2():
    print "test2!"


# モジュールのインポート (拡張子を覗いたファイル名を指定)
import echotest

# モジュールで定義されたメソッドの利用
echotest.echo1()

# ローカルな名前に代入して利用
method1 = echotest.echo1
method1()

パッケージについて

TODO: __init__.py など

モジュール検索について

・モジュールはカレントディレクトリ、環境変数 PYTHONPATH の順に探される。
・実際には、モジュールは変数 sys.path で指定されたディレクトリのリストから検索される。

パッケージの利用

パッケージ (package) は、Python のモジュール名前空間を
``ドット付きモジュール名 (dotted module names)'' を使って構造化する手段。

モジュール検索PATHの追加

import sys,os
sys.path.append('ディレクトリ')

ファイル一覧

# coding: utf-8

import sys,os
import glob
import re

path = os.path.abspath(os.path.dirname(__file__))

# globで検索
files = glob.glob(path + "/*.md")
for file in files:
    print(file)

# os.listdirで検索
pattern = r".*\.md$"
files = os.listdir(path)
for file in files:
    match = re.match(pattern , file)
    if match:
        print file

呼び出し元ファイルのフルパスを取得する

呼び出し元ファイルのフルパスを取得する

import inspect

print(inspect.stack()[1].filename)

簡易Webサーバ

サーバロジックを書きたい場合は pythonでWebサーバを書いてみる を参照。

python -m http.server 8000 -b localhost

※-b を指定しない場合は、localhost 以外にも公開される。( -b 0.0.0.0 と同じ)


トップ   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS