オラクる。

oracle専門ブログにしてみようかな~っと

カテゴリ: Python

pythonの実行時にコマンドライン引数を参照することが出来ます。

スクリプト
import sys

param = sys.argv

print (param)

print ("第一引数:" + param [1])
print ("第二引数:" + param [2])
print ("第三引数:" + param [3]) 

実行結果
C:\Users\>python 1.py this is a pen
['1.py', 'this', 'is', 'a', 'pen']
第一引数:this
第二引数:is
第三引数:a

pythonのコマンドライン引数は複数指定することが出来ます。
それぞれの引数は空白で区切ります。

また、指定したコマンドライン引数はsys.argv関数の返り値を利用することで取得します。
sys.argv関数の返り値は配列です。
それぞれ要素番号0は自身のファイル名
要素番号1以降がコマンドライン引数になります。 

リスト型の場合、要素名は0,1,2,・・・の数字でしたが、ディクショナリ型の場合、要素名は指定の文字列になります。
ディクショナリ型の初期化は変数名 = [要素名:値,要素名:値・・・]になります。

・値の初期化
スクリプト
test_dict_1 = {'year':'2014','month':'11','day':'25'}

print (test_dict_1)

print ('=================================')

for i in test_dict_1:
print (i)
print (test_dict_1[i])
print ('=================================')

実行結果
{'month': '11', 'day': '25', 'year': '2014'}
=================================
month
11
=================================
day
25
=================================
year
2014
================================= 

ディクショナリ型の値の初期化と表示を行なっています。
ディクショナリ型は{ }で初期化を行ないます。

・値の取得
スクリプト
test_dict_1 = {'year':'2014','month':'11','day':'25'}

print (test_dict_1)

print ('=================================')

print (test_dict_1['year'])

print ('=================================')

print (test_dict_1.get('year'))
print (test_dict_1.get('years'))

print ('=================================')

print (test_dict_1.get('year','not found'))
print (test_dict_1.get('years','not found')) 

実行結果
{'day': '25', 'month': '11', 'year': '2014'}
=================================
2014
=================================
2014
None
=================================
2014
not found

値の取得はディクショナリ名['要素名']で行ないます。
ここで存在しない要素名を指定した場合はエラーが発生します。
また、ディクショナリ名.get('要素名')でも値を取得することが出来ますが、こちらの場合、要素名が存在しない場合、エラーではなく「None」を返します。
なお、要素名が存在しない場合の表示はget関数の第二引数で指定することが出来ます。

・値の追加
スクリプト
test_dict_1 ={}

print (test_dict_1)

print ("============================")

test_dict_1['year'] = '2014'
test_dict_1['month'] = '11'
test_dict_1['day'] = '26'

print (test_dict_1)

実行結果
{}
============================
{'month': '11', 'year': '2014', 'day': '26'}

値を空にしてディクショナリ型の初期化を行なった後、「ディクショナリ名['要素名']=値」で値を追加しています。

・値の削除
スクリプト
test_dict_1 ={'year':'2014','month':'11','day':'26'}

print (test_dict_1)

print ("============================")

del test_dict_1['year']

print (test_dict_1) 

実行結果
{'day': '26', 'year': '2014', 'month': '11'}
============================
{'day': '26', 'month': '11'} 

ディクショナリ型の削除を行なう場合、del関数を利用します。 

pythonでのリストの扱い方を確認します。
前回紹介したタプルとの違いは初期化後に値を変更できるかです。

・初期化と表示
スクリプト
test_list1 = ['python','-','izm','.','com']

print (test_list1)

print ('-------------------------------')

for i in test_list1:
print (i)

結果
['python', '-', 'izm', '.', 'com']
-------------------------------
python
-
izm
.
com 

リストは[ ]で初期化を行ないます。
スクリプトではfor ~ in ~文を使い、リストの各値を取得、表示しています。

・値の追加
スクリプト
test_list1 = []

print (test_list1)

print ('-------------------------------')

test_list1.append('this')
test_list1.append('is')
test_list1.append('a')
test_list1.append('pen')
test_list1.append('.')

print (test_list1) 

結果
[]
-------------------------------
['this', 'is', 'a', 'pen', '.'] 

配列への要素の追加は「配列.append(値)」で行ないます。

・値の挿入
スクリプト
test_list1 = ['python','izm','com']

print (test_list1)

print ('-------------------------------')

test_list1.insert(1,'-')
test_list1.insert(3,'.')

print (test_list1)

test_list1.insert(0,'http://')

print (test_list1)

実行結果
['python', 'izm', 'com']
-------------------------------
['python', '-', 'izm', '.', 'com']
['http://', 'python', '-', 'izm', '.', 'com'] 

値の挿入は配列.insertで行ないます。
例えば「test_list1.insert(1,'-')」は1番目の要素の後ろに「-」を挿入します。
第一引数に0を指定した場合は要素の先頭に追加します。

・値の削除
スクリプト
test_list1 = ['1','2','3','2','4']

print (test_list1)

print ('-------------------------------')

test_list1.remove('2')

print (test_list1)

実行結果
['1', '2', '3', '2', '4']
-------------------------------
['1', '3', '2', '4'] 

値の削除は配列.removeで行なうことが出来ます。
第一引数で指定した文字列が最初に見つかった要素を削除します。

スクリプト
test_list1 = ['1','2','3','2','4']

print (test_list1)

print ('-------------------------------')

print (test_list1.pop(1))
print (test_list1)

print (test_list1.pop())
print (test_list1)

実行結果
['1', '2', '3', '2', '4']
-------------------------------
2
['1', '3', '2', '4']
4
['1', '3', '2']

もしくは、配列.popで削除することも出来ます。
第一引数で指定したインデックス番号の削除を行ないます。
また、何も指定しなかった場合は末尾の削除を行ないます。
それぞれ削除した値を返り値とします。 

タプルとはあんまり聞かれない言葉ですが、複数の要素を一つの値として取り扱うことの出来る型です。
リスト型と似ていますが、タプル型は初期化後に値を変更することが出来ません。
また、各要素のデータ型は同一である必要がありません。
各要素は「タプル名[要素番号]」で取得できます。

今回のスクリプトでは関数の返り値にタプルを使用しています。

・スクリプト
import datetime

def getToday():
today = datetime.datetime.today()
value = (today.year,today.month,today.day)
return value

test_tuple = getToday()

print (test_tuple)
print (test_tuple[0])
print (test_tuple[1])
print (test_tuple[2])

・実行結果
(2014, 11, 22)
2014
11
22 

今回はモジュールの作成方法と利用方法を確認します。
モジュールとして別ファイルを作成し、本体からはimportで作成したモジュールを読み込んで使えるようにするという感じです。

・スクリプト 
class testclass:
def __init__(self):
print ("create testclass")

def test_method(self,str):
print ("call test method")
print (str)

→上記モジュールをtestmodule.pyというファイル名で本体のスクリプトと同じフォルダに配置します。 

import testmodule
testclass1 = testmodule.testclass()
testclass1.test_method("1")

from testmodule import testclass
testclass1 = testclass()
testclass1.test_method("2") 

→まず、「import testmodule」でモジュールを読み込みます。
その後、モジュール名.クラス名でtestclassの初期化を行ないます。
初期化時にモジュールの「def __init__(self):」内の処理が読み込まれます。
初期化後に、testclass内の関数test_methodを読み込みます。

また、import時に「from モジュール名 import クラス名」と指定することで、 初期化時にモジュール名を記載する必要が無くなります。

・実行結果
create testclass
call test method
1
create testclass
call test method
2
 

このページのトップヘ