Python

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の指定


  1. ウインドウ
  2. 設定
  3. PyDev > インタープリター > Pythonインタープリター
  4. 新規
  5. インストールしたパスを指定
  6. 適用

プロジェクト作成


  1. ファイル
  2. 新規
  3. プロジェクト
  4. PyDev
  5. Pydevプロジェクト
  6. プロジェクト名、保存場所などを入力する

開発


開発時はビューをPythonに切り替える。
実行のショートカットはデフォルトはF9。

パッケージのインストール


バンドルのPythonの場合、この方法では正常にインストールされないので別途Pythonをインストールすること

  1. ウインドウ
  2. 設定
  3. PyDev > インタープリター > Pythonインタープリター
  4. Install/Uninstall with pip
  5. Command to executeの<package>部分を任意のパッケージ名に変更する
  6. 実行
  7. 閉じる


基本文法


Hello World


print("Hello World")

コメント



変数


共通単値変数





真偽値


True
False

順序配列











連想配列








集合(Set)




比較演算


一致(数値・文字列)


$int1 == $int2

不一致(数値・文字列)


$int1 != $int2

数値大小


$int1 < $int2

$int1 <= $int2

$int1 > $int2

$int1 >= $int2

正規表現一致




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



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


存在しない

文字列操作





連結


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番目には実行したスクリプトのフルパスが入る。


テキストファイル操作


オープン


with構文の場合、クローズが不要
file=open("/tmp/file")
or
with open("/tmp/file") as file:
    #処理内容

リード


ファイル全体を取得




一行ずつ取得


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:
    #処理内容

ライト




ネイティブコマンド実行


my @result1 = `ls $optionByPerl`;

my $result2 = `date`;
chomp($result2);
print("$result2\n");


標準関数


数値系


int


整数型に変換する
int("10")
int(1.1)

文字列系


len


文字列長を求める

ファイル系


unlink


ファイルを削除する


その他




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-connector
or
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()

Notice: Trying to get property 'queue' of non-object in /usr/local/wordpress/wp-includes/script-loader.php on line 2876

Warning: Invalid argument supplied for foreach() in /usr/local/wordpress/wp-includes/script-loader.php on line 2876