2016年02月06日 My first python programming [長年日記]
_ My first python programming
stdio
$ cat p001_stdio.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
import sys
print 'This is a string'
input_string = raw_input('Input: ')
print 'input_string is a (' + input_string + ')'
sys.stdout.write('Input: ')
rec = sys.stdin.readline()
rec = rec.rstrip('\r\n')
sys.stdout.write('rec is a (%s)\n' % (rec))
$ ./p001_stdio.py This is a string Input: My first python programming input_string is a (My first python programming) Input: はじめてのパイソン rec is a (はじめてのパイソン)
variable
$ cat p002_variable.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
# No need define for using variable.
# Variable is defined, when initialize.
#
var_str1 = 'ascii_string'
var_str2 = u'漢字の文字列です'
var_int= 123
var_real = 123.456
print 'var_str1 is a ' + var_str1
print 'var_str2 is a ' + var_str2.encode('UTF-8')
print 'var_int is a %d' % (var_int)
print 'var_real is a %7.3f' % (var_real)
$ ./p002_variable.py var_str1 is a ascii_string var_str2 is a 漢字の文字列です var_int is a 123 var_real is a 123.456
array
$ cat p003_array.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
var_array = ('ascii_string', 123, u'漢字文字列', 456.789)
print 'var_array[0] is a %s' % (var_array[0])
print 'var_array[1] is a %s' % (var_array[1])
print 'var_array[2] is a %s' % (var_array[2].encode('UTF-8'))
print 'var_array[3] is a %s' % (var_array[3])
var_hash = {'lemon':'yellow', 'strawberry':'red', 'orange':'orange'}
print 'var_hash["lemon"] is a %s' % (var_hash['lemon'])
print 'var_hash["strawberry"] is a %s' % (var_hash['strawberry'])
print 'var_hash["orange"] is a %s' % (var_hash['orange'])
$ ./p003_array.py var_array[0] is a ascii_string var_array[1] is a 123 var_array[2] is a 漢字文字列 var_array[3] is a 456.789 var_hash["lemon"] is a yellow var_hash["strawberry"] is a red var_hash["orange"] is a orange
operator
$ cat p004_operator.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
print "'abc' + 'def' is a %s" % ('abc' + 'def')
print "'abc' * 2 is a %s" % ('abc' * 2)
print "100 + 200.123 is %7.3f" % (100 + 200.123)
print "200.123 - 100 is %7.3f" % (200.123 - 100)
print "100 * 1.08 is %d" % (100 * 1.08)
print "1 / 3 is %f" % (1 / 3)
print "1.0 / 3 is %f" % (1.0 / 3)
print "3 ** 2 is %d" % (3 ** 2)
print "7 %% 5 is %d" % (7 % 5)
print "0x10 | 0x1 is 0x%02x" % (0x10 | 0x1)
print "0x81 & 0x7f is 0x%02x" % (0x81 & 0x7f)
print "0xFF ^ 0xF0 is 0x%02x" % (0xFF ^ 0xF0)
$ ./p004_operator.py 'abc' + 'def' is a abcdef 'abc' * 2 is a abcabc 100 + 200.123 is 300.123 200.123 - 100 is 100.123 100 * 1.08 is 108 1 / 3 is 0.000000 1.0 / 3 is 0.333333 3 ** 2 is 9 7 % 5 is 2 0x10 | 0x1 is 0x11 0x81 & 0x7f is 0x01 0xFF ^ 0xF0 is 0x0f
if
$ cat p005_if.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
wk1 = 'abc'
wk2 = 'def'
if wk1 == wk2:
	print '%s == %s\n' % (wk1, wk2)
elif wk1 > wk2:
	print '%s > %s\n' % (wk1, wk2)
else:
	print '%s < %s\n' % (wk1, wk2)
if wk1 != wk2:
	print '%s is not %s\n' % (wk1, wk2)
else:
	print '%s is equal to %s\n' % (wk1, wk2)
if (wk1 == 'abc' and
    wk2 == 'def'):
	print '%s is abc and %s is def\n' % (wk1, wk2)
else:
	print '%s is not abc or %s is not def\n' % (wk1, wk2)
$ ./p005_if.py abc < def abc is not def abc is abc and def is def
while
$ cat p006_while.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
import sys
rec = sys.stdin.readline()
while rec:
	rec = rec.rstrip('\r\n')
	sys.stdout.write('output = (%s)\n' % (rec))
	rec = sys.stdin.readline()
$ ./p006_while.py My first python programming output = (My first python programming) はじめてのパイソン output = (はじめてのパイソン)
for
$ cat p007_for.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
var_array = (123, 'abc', u'あいう', 456.789)
for i in var_array:
	if isinstance(i, unicode):
		print i.encode('UTF-8')
	else:
		print i
var_hash = {'lemon':'yellow', 'strawberry':'red', 'orange':'orange'}
for i in var_hash:
	print 'var_hash["%s"] is a %s' % (i, var_hash[i])
for i in sorted(var_hash.keys()):
	print 'var_hash["%s"] is a %s' % (i, var_hash[i])
$ ./p007_for.py 123 abc あいう 456.789 var_hash["orange"] is a orange var_hash["strawberry"] is a red var_hash["lemon"] is a yellow var_hash["lemon"] is a yellow var_hash["orange"] is a orange var_hash["strawberry"] is a red
file
$ cat p008_file.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
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()
$ ./p008_file.py line 1 line 2 line 3 $ cat p008_file.txt line 1 line 2 line 3
regex
$ cat p009_regex.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
import re
if re.search('^abc.*def$', 'abcpoipoidef'):
	print 'True'
else:
	print false
print re.sub('abc(.*)def$', r'ABC\1DEF', 'abcpoipoidef')
for i in re.split('p.*i', 'abcpoipoidef'):
	print i
$ ./p009_regex.py True ABCpoipoiDEF abc def
string
$ cat p010_string.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
var_str = u'abcあいうdef'
print var_str[1]
print var_str[3].encode('UTF-8')
print var_str[3:6].encode('UTF-8')
print len(var_str)
list = ('abc', 123, u'あいう', 123.456)
var_str = 'str1 = %s, num1 = %d, str2 = %s num2 = %7.3f\n' % list
print var_str.encode('UTF-8')
i = 0
while i < len(list):
	if isinstance(list[i], unicode):
		print list[i].encode('UTF-8')
	else:
		print list[i]
	i += 1
$ ./p010_string.py b あ あいう 9 str1 = abc, num1 = 123, str2 = あいう num2 = 123.456 abc 123 あいう 123.456
function
$ cat p011_function.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
import sys
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))
 $ ./p011_function.py
 10 + 20 is 30
try
$ cat p012_try.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
import sys
try:
	print 1 / 0
except ZeroDivisionError:
	print u'ゼロ割りエラー発生!'.encode('UTF-8')
print u'終了'.encode('UTF-8')
try:
	print 1 / 0
except:
	print u'エラー発生!'.encode('UTF-8')
	print sys.exc_info()[0]
print u'終了'.encode('UTF-8')
$ ./p012_try.py ゼロ割りエラー発生! 終了 エラー発生! <type 'exceptions.ZeroDivisionError'> 終了
day and time
$ cat p013_daytime.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
import time
daytime = time.strftime('%Y.%m.%d(%w) %H:%M:%S')
print daytime
struct_time = time.strptime(daytime, '%Y.%m.%d(%w) %H:%M:%S')
print struct_time
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)
print daytime
$ ./p013_daytime.py 2016.02.06(6) 00:47:37 time.struct_time(tm_year=2016, tm_mon=2, tm_mday=6, tm_hour=0, tm_min=47, tm_sec=37, tm_wday=5, tm_yday=37, tm_isdst=-1) 2016.02.07(0) 00:47:37
filesystem
$ cat p014_filesystem.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
import os
import shutil
tmppath = 'p014_filesystem.tmp'
os.mkdir(tmppath)
if os.path.exists(tmppath):
	print "指定のファイルもしくはディレクトリが存在しています。"
	if os.path.isfile(tmppath):
		print "指定のパスはファイルです。"
	if os.path.isdir(tmppath):
		print "指定のパスはディレクトリです。"
os.rmdir(tmppath)
#shutil.rmtree(tmppath)
f = open(tmppath, 'w')
f.write("line1\n")
f.close()
if os.path.exists(tmppath):
	print "指定のファイルもしくはディレクトリが存在しています。"
	if os.path.isfile(tmppath):
		print "指定のパスはファイルです。"
	if os.path.isdir(tmppath):
		print "指定のパスはディレクトリです。"
os.unlink(tmppath)
print 'current working directory is ' + os.getcwd()
for i in os.listdir("."):
	if os.path.isfile(i):
		print i + "はファイルです。"
	elif os.path.isdir(i):
		print i + "はディレクトリです。"
	else:
		print i + "は不明です。"
$ ./p014_filesystem.py 指定のファイルもしくはディレクトリが存在しています。 指定のパスはディレクトリです。 指定のファイルもしくはディレクトリが存在しています。 指定のパスはファイルです。 current working directory is /home/m-ito/tmp/python p011_function.pyはファイルです。 p002_variable.pyはファイルです。 p016_client.pyはファイルです。 p001_stdio.pyはファイルです。 p010_string.pyはファイルです。 p017_sqlite.pyはファイルです。 p006_while.pyはファイルです。 p016_single_server.pyはファイルです。 p009_regex.pyはファイルです。 p004_operator.pyはファイルです。 p007_for.pyはファイルです。 p005_if.pyはファイルです。 p016_multi_server.pyはファイルです。 p008_file.pyはファイルです。 p014_filesystem.pyはファイルです。 p012_try.pyはファイルです。 p003_array.pyはファイルです。 p008_file.txtはファイルです。 p017_sqlite.dbはファイルです。 p015_class.pyはファイルです。 p013_daytime.pyはファイルです。
class
$ cat p015_class.py #! /usr/bin/python # -*- coding: utf-8 -*- 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'
$ ./p015_class.py oSw is OFF oSw is ON oToggleSw is OFF oToggleSw is ON oToggleSw is OFF
client
$ cat p016_client.py #! /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 1: msg = raw_input() s.send(msg) data = s.recv(1024) print data s.close()
server(single)
$ cat p016_single_server.py
#! /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 1:
	(conn, addr) = s.accept()
	data = conn.recv(BUFSIZE)
	while data:
		conn.send(data )
		data = conn.recv(BUFSIZE)
	conn.close()
server(multi)
$ cat p016_multi_server.py
#! /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 1:
	(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()
sqlite3
$ cat p017_sqlite.py
#! /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()
$ ./p017_sqlite.py テーブルを作成する 初期データセットアップ 初期データセットアップ2 2重キーなので追加できません(001) 2重キーなので追加できません(002) 2重キーなので追加できません(003) 全件検索 001,山田 太郎,本社 002,山田 花子,営業第1課 003,山田 次郎,営業第2課 〜課のみ検索 002,山田 花子,営業第1課 003,山田 次郎,営業第2課 id=001を山田 三郎に更新 001,山田 三郎,本社 id=002を削除 001,山田 三郎,本社 003,山田 次郎,営業第2課 ロールバック 全件検索 by fetchone() 001,山田 三郎,本社 002,山田 花子,営業第1課 003,山田 次郎,営業第2課
argument
$ cat p018_args.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
import sys
print 'sys.argv=', sys.argv
print 'len(sys.argv)=(%d)' % (len(sys.argv))
i = 0
while i < len(sys.argv):
        print 'sys.argv[%d]=%s' % (i, sys.argv[i])
        i += 1
for i in sys.argv:
        print i
$ ./p018_args.py argv1 引数2 argv3 引数4 sys.argv= ['./p018_args.py', 'argv1', '\xe5\xbc\x95\xe6\x95\xb02', 'argv3', '\xe5\xbc\x95\xe6\x95\xb0\xef\xbc\x94'] len(sys.argv)=(5) sys.argv[0]=./p018_args.py sys.argv[1]=argv1 sys.argv[2]=引数2 sys.argv[3]=argv3 sys.argv[4]=引数4 ./p018_args.py argv1 引数2 argv3 引数4
[ツッコミを入れる]