2010年02月06日 スタイルシート(CSS)儂(わし)的解釈によるメモ
_ スタイルシート(CSS)儂(わし)的解釈によるメモ
例によって自分勝手な解釈、用語でメモメモっと...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=euc-jp"> <title>CSS sample</title> <style TYPE="text/css"> <!--
ヘッダー部で定義する場合は<style>タグと<!--で開始。
/*
* コメントも書けるよ
*/
H3, H4 {
color: red;
background: yellow
}
タグ(<h3><h4>)に対するスタイルの指定。
P.green {
color: green;
}
タグ(<p>)に指定するクラス(class="green")に対するスタイルの指定。
ちなみに、タグ中に指定するクラスは class="hoge foo bar" のように複数指定が可能(2011.12.15 追記)。
また、
P.green span{
color: green;
}
とした場合は、「class="green"を指定した<p>タグの内部の<span>タグ」に対するスタイル指定となる(2011.12.15 追記)。
*.red {
color: red;
}
クラス(class="red")に対するスタイルの指定。
#blue {
color: blue;
}
ID(id="blue")に対するスタイルの指定。
/* hover : マウスが乗った時
* link : リンク
* visited : クリック済のリンク
* active : クリックされた時
* focus : TABキーで選択された時
*/
:hover {
color: blue;
}
疑似クラス(hover)に対するスタイルの指定(2011.12.15 追記)。
*.iro_shitei {
color: red;
}
文字色の指定。
*.back_iro_shitei {
background: #FF0000; /* #RRGGBB */
}
文字の背景色の指定。
*.soto_yohaku {
/* margin: 3em; 下記の4つをまとめて指定する場合 */
margin-top: 3em; /* 3文字の余白 */
margin-bottom: 3em; /* 3文字の余白 */
margin-right: 3em; /* 3文字の余白 */
margin-left: 3em; /* 3文字の余白 */
border: 1px solid gray;
}
マージンの指定。指定したタグの外側の余白幅。
*.uchi_yohaku {
/* padding: 3em; 下記の4つをまとめて指定する場合 */
padding-top: 3em; /* 3文字の余白 */
padding-bottom: 3em; /* 3文字の余白 */
padding-right: 3em; /* 3文字の余白 */
padding-left: 3em; /* 3文字の余白 */
border: 1px solid gray;
}
パディングの指定。指定したタグの内側の余白幅。
*.waku {
/* border: 1px solid gray; 下記の4つをまとめて指定する場合 */
border-top: 1px none red;
border-bottom: 3px dotted green;
border-right: 5px dashed blue;
border-left: 7px double black;
}
枠線の指定。
*.hide {
/* block, inline, list-item, none */
display: none;
}
表示方法の指定
- block : ブロック要素として表示
- inline : インライン要素として表示
- list-item : リストの要素として表示
- none : 表示しない(領域も無くなる)
*.basyo_static {
position: static; /* 既定の場所 */
border: 1px solid gray;
}
表示位置の指定。デフォルトの位置。
*.basyo_abs {
position: absolute; top: 2em; left: 4em;
border: 1px solid gray;
}
指定したタグの親要素の左上を原点とする表示位置の指定。
*.basyo_rel {
position: relative; top: 2em; left: 4em;
border: 1px solid gray;
}
デフォルトの表示位置を原点とする位置指定。
*.basyo_fix {
position: fixed; top: 2em; left: 4em;
border: 1px solid gray;
opacity: 0.5; /* for Firefox */
filter: alpha(opacity=50); /* for Internet Explorer */
color: black;
background-color: pink;
}
ブラウザの左上を原点とする表示位置の指定。スクロールの影響を受けない。IE6以前ダメ。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/loose.dtd">
上記のように、htmlファイルの先頭で <!DOCTYPE ...> 宣言していれば、IE7以降ではOK。
あと、ついでに opacity, filter を使って透明度を指定(背景が透けて見える)。
*.gazou_basyo {
float: right; /* left, right, none */
width: 120px;
height: 90px;
}
右または左に回り込む位置指定。
*.invis {
/* visible, hidden, inherit */
visibility: hidden;
}
表示、非表示の指定。表示領域は保持される。
*.indent {
text-indent: 1em;
border: 1px solid gray;
}
字下げの指定。
*.text_basyo {
text-align: center; /* left, right, center, inherit */
border: 1px solid gray;
}
センタリング等の指定。
*.text_kazari {
text-decoration: line-through; /* none, underline, overline, line-through, blink, inherit */
border: 1px solid gray;
}
文字列飾りの指定。
*.table_cell {
empty-cells: show; /* show, hide, inherit */
}
テーブルの空セルに対する枠表示の指定。
*.ime_on {
ime-mode: active; /* auto, active, inactive, disabled */
}
かな漢字変換の指定
--> </style>
-->, </style>で閉じる。
<link rel="stylesheet" type="text/css" href="csssample.css">
外部ファイル(csssample.css)にスタイルシートをまとめる事もできる。
</head>
<body> <h1>CSS sample</h1> <hr /> <h2>指定の仕方(その1)</h2> タグに「style=」パラメータを指定して行う。 <blockquote> 一部だけ<span style="color:red;">赤文字</span>にしてみる。 </blockquote>
タグに直接スタイルを指定することもできる。
<hr /> <h2>指定の仕方(その2)</h2> ヘッダー部分でタグのスタイルをまとめて指定する。 <blockquote> 一部だけ<h3>色を変えて</h3>みる。 </blockquote>
<hr /> <h2>指定の仕方(その3)</h2> ヘッダー部分でタグに対応するクラスのスタイルをまとめて指定する。 <blockquote> <p class="green"> 段落全体の色を変えてみる。 </p> </blockquote>
<hr /> <h2>指定の仕方(その4)</h2> ヘッダー部分でクラスのスタイルをまとめて指定する。 <blockquote> 一部だけ<span class="red">色を変えて</span>みる。 </blockquote>
<hr /> <h2>指定の仕方(その5)</h2> ヘッダー部分でIDのスタイルをまとめて指定する。 <blockquote> 一部だけ<span id="blue">色を変えて</span>みる。 </blockquote>
<hr /> <h2>指定の仕方(その6)</h2> 外部ファイルでスタイルをまとめて指定する。 <blockquote> 一部だけ<span class="blue_yellow">色を変えて</span>みる。 </blockquote>
<hr /> <h2>色の指定 color: (既出ですが)</h2> <blockquote> 一部だけ<span class="iro_shitei">色を変えて</span>みる。 </blockquote>
<hr /> <h2>背景色の指定 background: (既出ですが)</h2> <blockquote> 一部だけ<span class="back_iro_shitei">色を変えて</span>みる。 </blockquote>
<hr /> <h2>マージンの指定 margin(-top,-bottom,-right,-left):</h2> <blockquote class="soto_yohaku"> マージンは外側の余白。 </blockquote>
<hr /> <h2>パディングの指定 padding(-top,-bottom,-right,-left):</h2> <blockquote class="uchi_yohaku"> パディングは内側の余白。 </blockquote>
<hr /> <h2>枠の指定 border(-top,-bottom,-right,-left):</h2> <blockquote class="waku"> ワクワクする枠...。 </blockquote>
<hr /> <h2>表示の仕方を指定 display:</h2> <blockquote> 括弧の中は(<span class="hide">見えたら</span>)ダメ。 </blockquote>
<hr /> <h2>場所の指定 position: (static)</h2> <blockquote> 場所の指定 <span class="basyo_static">static(既定の場所)</span> </blockquote>
<hr /> <h2>場所の指定 position: (absolute)</h2> <blockquote> 場所の指定 <span class="basyo_abs">absolute(親要素の左上を原点とする)</span> </blockquote>
<hr /> <h2>場所の指定 position: (relative)</h2> <blockquote> 場所の指定 <span class="basyo_rel">relative(規定の場所からの相対位置)</span> </blockquote>
<hr /> <h2>場所の指定 position: (fixed IEダメ)</h2> <blockquote> 場所の指定 <span class="basyo_fix">fixed(スクロールせずに絶対位置に固定。IEではダメ)</span> </blockquote>
<hr /> <h2>レイアウト指定 float:</h2> <img src="http://myh.no-ip.org/~m-ito/lib100/lib100_1.jpg" class="gazou_basyo" /> 画像の説明がいろいろと入るわけですが、面倒なので適当な文章を入力してます。 <br style="clear: both;"> ここ以降は回り込みが解除されているはず。
<hr /> <h2>表示の仕方を指定 visibility:</h2> <blockquote> 括弧の中は(<span class="invis">見えたら</span>)ダメ。 </blockquote>
<hr /> <h2>字下げ text-indent:</h2> <blockquote class="indent"> 字下げで表示。 </blockquote>
<hr /> <h2>文字の表示位置 text-align:</h2> <blockquote class="text_basyo"> センタリングしてみました。 </blockquote>
<hr /> <h2>文字の飾り text-decoration:</h2> <blockquote> <span class="text_kazari">打ち消し線。</span> </blockquote>
<hr /> <h2>テーブルの枠を常に表示 empty-cells: (IEダメ?)</h2> <table border="1" class="table_cell"> <tr><th>header1</th><th></th><th>header3</th></tr> <tr><td></td><td>data12</td><td></td></tr> <tr><td>data21</td><td></td><td>data23</td></tr> </table>
<hr /> <h2>日本語変換 ime-mode: (IE限定)</h2> <blockquote> <input type="text" class="ime_on" /> </blockquote> </body> </html>
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