その名の通り「Python覚えた事・忘れそうな事を個人用にメモしていくページ」です。
随時更新中
if文を1行で書く
result = aaa if aaa > 1 else 0
マルチスレッド
import threading # マルチスレッドでそれぞれのローソク足jsonを更新 def func1(): update_json_loop(60) def func2(): update_json_loop(300) def func3(): update_json_loop(3600) if __name__ == "__main__": thread_1 = threading.Thread(target=func1) thread_2 = threading.Thread(target=func2) thread_3 = threading.Thread(target=func3) thread_1.start() time.sleep(10) thread_2.start() time.sleep(10) thread_3.start()
APIリクエスト
import requests params = {"periods" : 60} response = requests.get("https://api.cryptowat.ch/markets/bitflyer/btcfxjpy/ohlc",params)
json化
data = response.json()
別ディレクトリ別ファイルのクラスを呼ぶ
メイン main.py
from model.price import Price Price.print_test()
呼ばれるクラス modelディレクトリのprice.py
class Price: def print_test(): print("print_test")
配列結合
# パターン1 tmp1 = [1, 2, 3] tmp2 = 4 tmp1.append(tmp2) # パターン2 tmp1 = [1, 2, 3] tmp2 = [4, 5] tmp1.extend(tmp2) tmp1.append(tmp2) # これだと [1, 2, 3, [4, 5]]になるので注意
PythonからPythonファイル実行
import subprocess subprocess.check_call(['python','child.py'])
コマンドライン引数で実行
python test.py a b c
# test.py import sys args = sys.argv print(args) print(args[1]) print(args[2]) print(args[3])
PythonからPythonファイル実行する際にコマンドライン引数で実行
import subprocess subprocess.call(['python','test.py', 'a', 'b', 'c'])
例外エラー処理
def hohoge(): while True: try: # 処理 except ccxt.BaseError as e: # err時処理
関数名
import inspect def aaa(): print(inspect.currentframe().f_code.co_name) aaa # aaaが出てくる
上で__name__とかやると__main__と出ます
if
if sex='男': is_man = True else: is_man = False
良くコロン:を忘れてエラーになります。。
三項演算子
is_man = True if sex='男' else False
.