Python memo
hello.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
import sys
sys.stdout.write('Hello\n')
args
import sys
args_count = len(sys.argv)
i = 0
while i < len(sys.argv):
print sys.argv[i]
i += 1
for i in sys.argv:
print i
stdio
import sys
print 'Print string with LF'
input_string = raw_input('Please input: ')
sys.stdout.write('Write string without LF')
rec = sys.stdin.readline() # Read line with CRLF
rec = rec.rstrip('\r\n') # Strip last CR and LF
sys.stdout.write('rec is a (%s)\n' % (rec)) # Write formated string like printf
variable
var_str1 = 'ascii_string'
var_str2 = u'漢字の文字列です' # UNICODE for internal expression
var_int= 123
var_real = 123.456
var_str2_utf8 = var_str2.encode('UTF-8')
var_str2_unicode = var_str2.decode('UTF-8')
wk = var_str2_utf8[0:3] # '漢' 3 bytes
wk = var_str2_unicode[0:3] # u'漢字の' 3 chars
list
var_list1 = ['ascii_string', 123, u'漢字文字列', 456.789]
wk = var_list1[2] # u'漢字文字列'
len = len(var_list1) # 4
var_list2 = []
i = 0
while i < 4:
var_list2.append("")
i += 1
var_list2[0] = 'ascii_string'
var_list2[1] = 123
var_list2[2] = u'漢字文字列'
var_list2[3] = 456.789
hash
var_hash = {'lemon':'yellow', 'strawberry':'red', 'orange':'orange'}
wk = var_hash["strawberry"] # 'red'
var_hash["addKey"] = "hogehoge"
operator
wk = 'abc' + 'def' # 'abcdef'
wk = 'abc' * 2 # 'abcabc'
wk = 10 + 20 # 30
wk = 10 - 20 # -10
wk = 10 * 20 # 200
wk = 10 / 20 # 0
wk = 10.0 / 20 # 0.5
wk = 3 ** 2 # 9
wk = 7 % 5 # 2
if
if wk1 == wk2:
print 'wk1 == wk2'
elif wk1 > wk2:
print 'wk1 > wk2'
else:
print 'wk1 < wk2'
if wk1 != wk2:
print 'wk1 != wk2'
else:
print 'wk1 == wk2'
if (wk1 == 'abc' and
wk2 == 'def'):
print 'wk1 == abc and wk2 == def'
else:
print 'wk1 != abc or wk2 != def'
while
import sys
rec = sys.stdin.readline()
while rec:
rec = rec.rstrip('\r\n')
sys.stdout.write(rec)
rec = sys.stdin.readline()
i = 0
while i < 10:
print i
i += 1
for
var_tuple = (123, 'abc', u'あいう', 456.789)
for i in var_tuple:
print i
var_hash = {'lemon':'yellow', 'strawberry':'red', 'orange':'orange'}
for i in var_hash:
print var_hash[i]
for i in sorted(var_hash.keys()):
print var_hash[i]
file
f = open('p008_file.txt', 'w')
f.write('line 1\n')
f.write('line 2\n')
f.write('line 3\n')
f.close()
f = open('p008_file.txt', 'r')
rec = f.readline()
while rec:
rec = rec.rstrip('\r\n')
print rec
rec = f.readline()
f.close()
regex
import re
if re.search('^abc.*def$', 'abcpoipoidef'):
print 'True'
else:
print false
wk = re.sub('abc(.*)def$', r'ABC\1DEF', 'abcpoipoidef') # ABCpoipoiDEF
wk = re.split('p.*i', 'abcpoipoidef') # [ 'abc', 'def' ]
string
var_str = u'abcあいうdef'
print var_str[1] # 'b'
print var_str[3] # 'あ'
print var_str[3:6] # 'あいう'
print len(var_str) # 9
wk_utf8 = var_str.encode('UTF-8')
wk_unicode = wk_utf8.decode('UTF-8')
wk_str = '123'
wk_int = int(wk_str)
wk_long = long(wk_str)
wk_int = 123
wk_str = str(wk_int)
wk_str = '12.34'
wk_float = float(wk_str)
wk_hex_str = hex(123) # '0x7b'
wk_hex_str = '%x' % (123) # '7b'
wk_int = int('0x7b', 16) # 123
wk_int = int('7b', 16) # 123
wk = ord('A') # 65
wk = chr(65) # 'A'
function
def add(i1, i2):
return i1 + i2
def printf(format, *list):
sys.stdout.write(format % list)
printf('%d + %d is %d\n', 10, 20, add(10, 20))
try
try:
print 1 / 0
except ZeroDivisionError:
print 'ゼロ割りエラー発生!'
try:
print 1 / 0
except:
print 'エラー発生!'
print sys.exc_info()[0]
daytime
import time
daytime = time.strftime('%Y.%m.%d(%w) %H:%M:%S') # 2016.12.03(6) 14:57:15 <- Sat
struct_time = time.strptime(daytime, '%Y.%m.%d(%w) %H:%M:%S')
epoch_sec = time.mktime(struct_time) + (24 * 60 * 60)
struct_time = time.localtime(epoch_sec)
daytime = time.strftime('%Y.%m.%d(%w) %H:%M:%S', struct_time) # 2016.12.04(0) 14:57:15 <- Sun
filesystem
import os
import shutil
os.mkdir('NewDir')
if os.path.exists('NewDir'):
print "指定のファイルもしくはディレクトリが存在しています。"
if os.path.isfile(tmppath):
print "指定のパスはファイルです。"
if os.path.isdir(tmppath):
print "指定のパスはディレクトリです。"
os.rmdir('NewDir')
#shutil.rmtree('NewDir')
f = open('NewFile', 'w')
f.write("line1\n")
f.close()
os.unlink('NewFile')
print 'current working directory is ' + os.getcwd()
for i in os.listdir("."):
print i
class
class MySwitch(object):
def __init__(self):
self.intSw = 0
def turnOn(self):
self.intSw = 1
def turnOff(self):
self.intSw = 0
def isOn(self):
return (self.intSw == 1)
def isOff(self):
return not isOn(self)
class MyToggleSwitch(MySwitch):
def __init__(self):
super(MyToggleSwitch, self).__init__()
def toggle(self):
if super(MyToggleSwitch, self).isOn():
super(MyToggleSwitch, self).turnOff()
else:
super(MyToggleSwitch, self).turnOn()
oSw = MySwitch()
if oSw.isOn():
print 'oSw is ON'
else:
print 'oSw is OFF'
oSw.turnOn()
if oSw.isOn():
print 'oSw is ON'
else:
print 'oSw is OFF'
oToggleSw = MyToggleSwitch()
if oToggleSw.isOn():
print 'oToggleSw is ON'
else:
print 'oToggleSw is OFF'
oToggleSw.toggle()
if oToggleSw.isOn():
print 'oToggleSw is ON'
else:
print 'oToggleSw is OFF'
oToggleSw.toggle()
if oToggleSw.isOn():
print 'oToggleSw is ON'
else:
print 'oToggleSw is OFF'
client
#! /usr/bin/python
# -*- coding: utf-8 -*-
import socket
import sys
HOST = '127.0.0.1'
PORT = 12345
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
while True:
msg = raw_input()
s.send(msg)
data = s.recv(1024)
print data
s.close()
multi_server
#! /usr/bin/python
# -*- coding: utf-8 -*-
import socket
import os
import sys
import signal
pid = os.fork() # バックグラウンドで実行、プロセスグループリーダーでなくなる、setsid()を呼べる状態になる
if pid < 0:
sys.exit(1) # fork失敗時は終了(1)
if pid > 0:
sys.exit(0) # 親プロセスは終了
os.setsid() # 新しいセッションを作成してセッション・リーダーになる、制御端末が切り離される
signal.signal(signal.SIGCHLD, signal.SIG_IGN) # SIHCHLDは無視する
signal.signal(signal.SIGHUP, signal.SIG_IGN) # SIGHUPは無視する
pid = os.fork() # プロセスグループリーダーでなくなる、新たに制御端末と結びつけなくなる
if pid < 0:
sys.exit(1)
if pid > 0:
sys.exit(0)
os.umask(0)
os.chdir("/")
os.close(0)
os.close(1)
os.close(2)
HOST = '127.0.0.1'
PORT = 12345
BACKLOG = 10
BUFSIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(BACKLOG)
while True:
(conn, addr) = s.accept()
pid = os.fork()
if pid == 0:
data = conn.recv(BUFSIZE)
while data:
conn.send(data)
data = conn.recv(BUFSIZE)
conn.close()
sys.exit(0)
else:
conn.close()
single_server
#! /usr/bin/python
# -*- coding: utf-8 -*-
import socket
import os
import sys
import signal
pid = os.fork()
if pid < 0:
sys.exit(1)
if pid > 0:
sys.exit(0)
os.setsid()
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
signal.signal(signal.SIGHUP, signal.SIG_IGN)
pid = os.fork()
if pid < 0:
sys.exit(1)
if pid > 0:
sys.exit(0)
os.umask(0)
os.chdir("/")
os.close(0)
os.close(1)
os.close(2)
HOST = '127.0.0.1'
PORT = 12345
BACKLOG = 10
BUFSIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(BACKLOG)
while True:
(conn, addr) = s.accept()
data = conn.recv(BUFSIZE)
while data:
conn.send(data )
data = conn.recv(BUFSIZE)
conn.close()
sqlite
#! /usr/bin/python
# -*- coding: utf-8 -*-
import sqlite3
import os
import sys
dbfile = './p017_sqlite.db'
try:
os.unlink(dbfile)
except OSError as e:
print 'OSError(%d)(%s)(%s)' % (e.errno, e.strerror, dbfile)
except:
print sys.exc_info()[0]
sys.exit(1)
conn = sqlite3.connect(dbfile)
c = conn.cursor()
print u'テーブルを作成する'.encode('UTF-8')
c.execute('''
create table t_test (
id text primary key,
name text,
syozoku text
)
'''
)
conn.commit()
print u'初期データセットアップ'.encode('UTF-8')
c.execute('''begin''')
init_data = (
('001', u'山田 太郎', u'本社'),
('002', u'山田 花子', u'営業第1課'),
('003', u'山田 次郎', u'営業第2課')
)
for i in init_data:
c.execute('''
insert into t_test
(id, name, syozoku)
values(?, ?, ?)
''',
i
)
conn.commit()
print u'初期データセットアップ2'.encode('UTF-8')
c.execute('''begin''')
init_data = (
('001', u'山田 太郎', u'本社'),
('002', u'山田 花子', u'営業第1課'),
('003', u'山田 次郎', u'営業第2課')
)
for i in init_data:
try:
c.execute('''
insert into t_test
(id, name, syozoku)
values(?, ?, ?)
''',
i
)
except sqlite3.IntegrityError:
print '2重キーなので追加できません(%s)' % (i[0])
except:
print sys.exc_info()[0]
sys.exit(1)
conn.commit()
print u'全件検索'.encode('UTF-8')
c.execute('''begin''')
c.execute('''select * from t_test''')
for row in c:
print ('%s,%s,%s' % row).encode('UTF-8')
print u'〜課のみ検索'.encode('UTF-8')
c.execute('''select * from t_test where syozoku like ?''', (u'%課',))
for row in c:
print ('%s,%s,%s' % row).encode('UTF-8')
print u'id=001を山田 三郎に更新'.encode('UTF-8')
c.execute('''update t_test set name = ? where id = ?''', (u'山田 三郎', '001'))
c.execute('''select * from t_test where id = ?''', ('001',))
for row in c:
print ('%s,%s,%s' % row).encode('UTF-8')
conn.commit()
print u'id=002を削除'.encode('UTF-8')
c.execute('''begin''')
c.execute('''delete from t_test where id = ?''', ('002',))
c.execute('''select * from t_test''')
for row in c:
print ('%s,%s,%s' % row).encode('UTF-8')
print u'ロールバック'.encode('UTF-8')
conn.rollback()
print u'全件検索 by fetchone()'.encode('UTF-8')
c.execute('''begin''')
c.execute('''select * from t_test''')
row = c.fetchone()
while row:
print ('%s,%s,%s' % row).encode('UTF-8')
row = c.fetchone()
conn.commit()
c.close()
[更新]
[戻る]
m-ito@myh.no-ip.org