Skip to content

Instantly share code, notes, and snippets.

@shiro01
Last active November 12, 2019 09:46
Show Gist options
  • Save shiro01/7f604b8577d3d0348ced846b45cfcd6a to your computer and use it in GitHub Desktop.
Save shiro01/7f604b8577d3d0348ced846b45cfcd6a to your computer and use it in GitHub Desktop.
Pythonメモ
https://www.python.jp/install/centos/index.html
https://docs.python.jp/3/library/venv.html
CentOSにpython3.6インストール手順
$ sudo yum -y install https://centos7.iuscommunity.org/ius-release.rpm
$ yum -y install python36u python36u-devel python36u-pip
仮想環境作成・有効化・ライブラリインストール・無効化
$ python3 -m venv ./myenv
$ source myenv/bin/activate
$ pip install --upgrade pip
$ pip install <ライブラリ>
$ deactivate
$ pip freeze > requirements.txt
$ pip install -r requirements.txt
$ pip freeze | xargs pip uninstall -y
# zip_longest サンプル
>>> from itertools import zip_longest
>>> a = [0, 0, 0, 0, 0]
>>> i = [1, 2, 3]
>>> a2 = zip_longest(a,i)
>>> [y is not None and y + x or 0 for x, y in a2]
[1, 2, 3, 0, 0]
>>> [y is not None and y + x or 0 for x, y in a2]
[]
# Pythonでクラス -------------
class class_test:
def __init__(self, arg):
self.num = arg
def show(self):
return self.num
def add(self, add_num):
self.num += add_num
return self.num
test = class_test(100)
print(test.show())
print(test.add(100))
# ------------------------------
# 月初のみ処理する。日時から日付を取得し01の場合を判定。
from datetime import datetime
a = datetime(2018, 12, 1, 0, 0, 0, 0)
for i in range(31):
if a.strftime('%d') == '{:0=2}'.format(i):
print(a)
# --------------------------------------
# python で再帰書いてみた。
import time
def hoge_r(x, sleep_time):
print('hoge')
time.sleep(1)
if x < sleep_time:
hoge_r(x + 1, sleep_time)
def hoge(sleep_time):
print('start')
hoge_r(0, sleep_time)
print('end')
hoge(5)
# --------------------------------------
# sampleのような辞書のリストを以下のような文字列に変換する
# hoge:001
# foo:001
# bar:001
#
# hoge:002
# foo:002
# bar:002
#
# hoge:003
# foo:003
# bar:003
sample = [
{'hoge':'001', 'foo':'001', 'bar':'001'},
{'hoge':'002', 'foo':'002', 'bar':'002'},
{'hoge':'003', 'foo':'003', 'bar':'003'}
]
def convert_dict_value_list_to_string(data):
def convert(dict_value):
return '\n'.join(['{0}:{1}'.format(key, dict_value[key]) for key in dict_value])
return '\n\n'.join([convert(dict_value) for dict_value in data])
print(convert_dict_value_list_to_string(sample))
# ファイル内容を全行読み込む --------------------------------------
def read_file_contents(file_path):
try:
with open(file_path, 'r') as f:
contents = f.read()
return contents
except Exception as e:
raise Exception('ファイル読み込み失敗: {0}'.format(e))
# --------------------------------------
# 下位階層で作成したライブラリを読み込むためにパスを追加する。
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
# 集計対象日を決定する(JSTで前日)
from datetime import datetime
from datetime import timedelta
def jst_datetime():
jst_datetime = datetime.now() + timedelta(hours=9) - timedelta(days=1)
return jst_datetime
# 日付文字列に変換
jst_datetime.strftime('%Y%m%d')
# openの前にディレクトリを新規作成する
import os
os.makedirs(new_dir_path, exist_ok=True)
# バージョンが古くディレクトリの有無を調べる必要がある場合
if not os.path.exists(new_dir_path):
os.makedirs(new_dir_path)
# クライアントを毎回生成すると時間がかかる。
TDS_API_KEY = ''
JOB_ID =
current_time = datetime.now()
with tdclient.Client(TDS_API_KEY, endpoint='https://api.treasuredata.com/') as td_client:
for i in range(500):
result = td_client.job_result(JOB_ID)
diff_time = datetime.now() - current_time
print("end. 1:実行時間: " + str(diff_time.seconds) + " sec")
current_time2 = datetime.now()
for i in range(500):
with tdclient.Client(TDS_API_KEY, endpoint='https://api.treasuredata.com/') as td_client:
result = td_client.job_result(JOB_ID)
diff_time = datetime.now() - current_time2
print("end. 2:実行時間: " + str(diff_time.seconds) + " sec")
# start
# end. 1:実行時間: 112 sec
# end. 2:実行時間: 407 sec
# end
reg = re.compile(r'^[a-zA-Z0-9_]+$')
reg.match(s) is not None
# filterを試してみる。
num_list2 = list(range(10,20)) # [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
even_list2 = filter(lambda x:x % 2 ==0, num_list2)
print(list(even_list2))
def is_double_list(d):
""" 2重配列かどうかを確認する
"""
if list == type(d) and 0 != len(d):
if list == type(d[0]) and 0 != len(d):
return True
else:
return False
def is_valid_data_event(data_type):
valid_data = {'a':False, 'b':False, 'c':True}
if data_type in valid_data:
return valid_data[data_type]
else:
print('unknown data type')
return False
[
{
"Id": "2",
"time": "1567385545273"
},
{
"Id": "4",
"time": "1567385554433"
},
{
"Id": "3",
"time": "1567385559453"
},
{
"Id": "1",
"time": "1567385564476"
}
]
sorted(a, key=lambda x: x['time'], reverse=True)
import logging
logging.basicConfig(
format='[%(asctime)s][%(filename)s#%(funcName)s:%(lineno)d][%(levelname)s] %(message)s',
datefmt='%Y/%m/%d %H:%M:%S',
level=logging.INFO
)
# lambda関数でのログ設定
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
formatter = logging.Formatter(
fmt='[%(levelname)s][%(asctime)s.%(msecs)dZ][%(aws_request_id)s][%(filename)s#%(funcName)s:%(lineno)d] %(message)s',
datefmt='%Y-%m-%dT%H:%M:%S'
)
for handler in logger.handlers:
handler.setFormatter(formatter)
こんなこともできる。
def hoge1():
print('1')
def hoge2():
print('2')
def hogestart():
d = [hoge1, hoge2]
for a in d:
print('aa')
a()
hogestart()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment