Python

最近管理しているサービスのレスポンスが落ちぎみ
ログ解析用のツールをpythonで作ってみようと
やり始めたら、まったく覚えてなくて笑った。1からやり直し


#ファイルの読込

f = open('file.name', 'r')
for line in f:
....

#文字列の分割

string.split(',');

#for文

test_list = [('A','B','C'),('B','C','D'),('C','D','E')]
for str1,str2,str3 in test_list:
  print(str1 + str2 + str3)

>ABC
>BCD
>CDE


#Dictのkey valueを取得するメソッド

dict.items() => key, value
dict.keys() => key
dict.values() => value

#Dict内の存在チェック

dict.has_key('key_name') : true/false
'key_name' in dict : true/false

#printの時、改行させたくない(,で)

print 'output_line',

#print 右寄せ、左寄せ

print('%15s' % 'Hello')
   Hello
print('%-15s' % 'Hello')
Hello


import os
# ディレクトリの存在(ディレクトリか?)チェック

os.path.isdir(_dir_path)

# ファイルの存在(ファイルか?)チェック

os.path.isfile(_fime_path)

# ファイルの削除

os.remove(_file_path)


#ログファイルの収集にsftp転送

import paramiko as ssh
try:
 conn = ssh.SSHClient()
 conn.set_missing_host_key_policy(ssh.AutoAddPolicy())
 conn.connect(ip, username=_user_name , password=_user_pass)
 sfconn = conn.open_sftp()
 sfconn.get(_source_path, _target_path)
finally:
 if conn:
  conn.close()

#ファイルAの末尾にファイルBのデータを追加

open( _fileA_path , "a").write(open(_fileB_path).read())

#連想配列の値でソート

import operator
result_list = sorted(result_list, key=operator.itemgetter(sort_key))

#python遅いわと思ったら俺がおぞすぎな件

for line in f:
 log_list = line[:-1].split(' ');
 result_list.append({'ip':log_list[0],'time':log_list[3],'display':log_list[6],'response':log_list[13] })

 result_list = sorted(result_list, key=operator.itemgetter(sort_key))

結論:インデントに注意