Contents
参考資料
Python チュートリアル
https://docs.python.org/ja/3/tutorial/index.html
開発
Pythonのインストール
Eclipse
EclipseにPythonがバンドルされているが、パッケージのインストールが正常にできない。
その為、別途インストールする。
最新版はこちらより入手可能。
デフォルトではWindowsは次のパスにインストールされる。
C:\Users\sainte\AppData\Local\Programs\Python
Linux
デフォルトではPython2が入っているので、Python3をインストールする
yum install -y https://centos7.iuscommunity.org/ius-release.rpm yum info "python3*" | grep ^Name | egrep -v - # 任意のバージョンを選択する(末尾のuの有無は提供元が違う程度) # 今回はより最新のパッチレベルを提供していたu有版を選択した yum install python36u python36u-tkinter python36u-test python36u-setuptools -y easy_install-3.6 pip
Eclipse
Pythonの指定
- ウインドウ
- 設定
- PyDev > インタープリター > Pythonインタープリター
- 新規
- インストールしたパスを指定
- 適用
プロジェクト作成
- ファイル
- 新規
- プロジェクト
- PyDev
- Pydevプロジェクト
- プロジェクト名、保存場所などを入力する
開発
開発時はビューをPythonに切り替える。
実行のショートカットはデフォルトはF9。
パッケージのインストール
バンドルのPythonの場合、この方法では正常にインストールされないので別途Pythonをインストールすること
- ウインドウ
- 設定
- PyDev > インタープリター > Pythonインタープリター
- Install/Uninstall with pip
- Command to executeの<package>部分を任意のパッケージ名に変更する
- 実行
- 閉じる
基本文法
Hello World
print("Hello World")
コメント
- 一行
# comment
- 複数行
"""comment1 comment2 comment3"""
変数
共通単値変数
- 宣言
不要
- 代入
i=1 str="abc"
- 参照
print(i) print(str)
真偽値
True False
順序配列
- 宣言
list = [1,2,3,4,5] # 多次元配列 list = [[1,2,3,4,5],[6,7,8,9]]
- 要素表示
print(list)
- 後方追加
list.append(6)
- 代入
list[0]=-1 # 末尾の要素に代入 list[-1]=-5
- 配列長
len(list)
- 参照
print(list[0])
- 配列連結
list = list+list
- 要素削除
list = [1,2,3,4,5] list[1:4] = [] # [1, 5]
連想配列
- 宣言
map = {"a": 123, "b": 456}
- 代入
map["a"] = 789 map["c"] = "XXX"
- 存在確認
"a" in map "a" not in map
- 参照
print(map["a"])
- 順序参照
for key, value in map.items(): print(key, value)
- 削除
del map["a"]
集合(Set)
- 宣言
set = {1,2,3,1} # print(set) # {1, 2, 3}
- 存在確認
1 in set 5 not in set
比較演算
一致(数値・文字列)
$int1 == $int2
不一致(数値・文字列)
$int1 != $int2
数値大小
$int1 < $int2
$int1 <= $int2 $int1 > $int2
$int1 >= $int2
正規表現一致
- 前方一致
import re print(re.match(r"[a-z]+", "aaa123")!=None) # True print(re.match(r"[a-z]+", "123aaa")!=None) # False
- 部分一致
import re print(re.search(r"[a-z]+", "123")!=None) # False print(re.search(r"[a-z]+", "123aaa456")!=None) # True print(re.search(r"^[a-z]+$", "123aaa456")!=None) # False
OR
$int1==$int2 or $int3!=$int4
AND
$int1==$int2 and $int3!=$int4
NOT
not $int1==$int2
制御構文
for
for i in range(5): print(i) # 0-4 for i in range(5,10): print(i) # 5-9
for each
- 配列変数から
for elm in {"a","b","c"}: print(elm)
while
i=0 while i < 10: print(i) i+=1
break
break
continue
continue
if
if x < 0: print("x < 0")
if else
if x < 0: print("x < 0") elif x == 0: print("x == 0") else: print("x > 0")
三項演算
val = "big" if n > 10 else "small"
switch case
存在しない
文字列操作
値
- 複数行
行末に”\”がある場合は改行されない。
print("""\ aaa\ bbb\ ccc """) #aaabbb #ccc
連結
str1+str2
部分切り取り
my $substring = substr($str, $start, $end);
置換
$str =~ s/abc/123/g;
探索(indexOf)
"abcde".find("d") #3
関数
def funcA(n): return n*2 def funcB(): return 1 print(funcA(1)) print(funcB())
コマンドライン引数
配列変数 sys.argv で与えられる。
配列要素0番目には実行したスクリプトのフルパスが入る。
- 例
引数の数のチェック
import sys if len(sys.argv) > 1 :
テキストファイル操作
オープン
with構文の場合、クローズが不要
file=open("/tmp/file")or
with open("/tmp/file") as file: #処理内容
リード
ファイル全体を取得
- 文字列オブジェクト
str = file.read()
- リスト
strList = file.readlines()
一行ずつ取得
for line in file: print(line)
クローズ
file.close()
書き込みオープン
新規、上書きオープン
with構文の場合、クローズが不要
file=open("/tmp/file", mode="w")or
with open("/tmp/file", mode="w") as file: #処理内容
新規オープン
ファイルが存在する場合はFileExistsErrorエラーになる
with構文の場合、クローズが不要
file=open("/tmp/file", mode="x")or
with open("/tmp/file", mode="x") as file: #処理内容
追記書き込みオープン
with構文の場合、クローズが不要
file=open("/tmp/file", mode="a")or
with open("/tmp/file", mode="a") as file: #処理内容
ライト
- 文字列
file.write(str)
- 文字列リスト
file.writelines(strList)
ネイティブコマンド実行
my @result1 = `ls $optionByPerl`; my $result2 = `date`; chomp($result2); print("$result2\n");
標準関数
数値系
int
整数型に変換する
int("10") int(1.1)
文字列系
len
文字列長を求める
ファイル系
unlink
ファイルを削除する
- 書式
unlink($filepath) - int(削除した個数)
その他
Hello World
#!/usr/bin/perl print("Content-type: text/html\n\n"); print("Hello World");
Tips
時刻
時間
import datetime now=datetime.datetime.now() year=now.year month=now.month day=now.day hour=now.hour minute=now.minute second=now.second microsecond=now.microsecond dayOfWeek=now.weekday()
日付
import datetime today=datetime.date.today()
指定時刻・日時
import datetime sometime = datetime.datetime(2019, 2, 24, 12, 10, 30) someday = datetime.datetime(2019, 2, 24)
文字列変換
import datetime str = '2019/2/24 12:30' someday = datetime.datetime.strptime(str, '%Y/%m/%d %H:%M') print(someday.strftime("%Y/%m/%d %H:%M"))
加減算
import datetime datetime.datetime.now()+datetime.timedelta(days=1)
データベース
MySQL
MySQL Connector
“mysql-connector”パッケージをインストールすること
pip install mysql-connectoror
python3.6 -m pip install mysql-connector
参考:https://dev.mysql.com/doc/connector-python/en/
Select
import mysql.connector connector = mysql.connector.connect( host="example.com", user="root", passwd="password", database="db1" ) cursor = connector.cursor() cursor.execute("select * from table1") result = cursor.fetchall() for row in result: print(dict(zip(cursor.column_names, row))) cursor.execute("select max(ID) from table2 where ID < %s", (10,)) maxId = cursor.fetchone()[0] cursor.close() connector.close()
Insert
import mysql.connector connector = mysql.connector.connect( host="example.com", user="root", passwd="password", database="db1" ) cursor = connector.cursor() SQL_INSERT = ("INSERT INTO table1 " "(COL1, COL2) " "VALUES (%(col1)s, %(col2)s)") parameters = { "col1": 100, "col2": "abc", } cursor.execute(SQL_INSERT, parameters) id = cursor.lastrowid connector.commit() cursor.close() connector.close()