■ArgumentParserでコマンドライン引数を渡す
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description='hogehoge')
parser.add_argument('input_path', help='this is input path')
parser.add_argument('output_dire', help='this is output directory')
parser.add_argument('-m','--message', default='hello world!')
parser.add_argument('-f','--flag', action='store_true') # 実行時に--flagが指定されているとTrue,そうでないときはFalse
args = parser.parse_args()
print(args.input_path)
■Json出力をいつも忘れる
def debug_output(suffix, **output_data):
"""for debugging"""
os.makedirs("debugging_Json", exist_ok=True)
for name, value in output_data.items():
output_json_name = f"{name}_{suffix}"
json_file_path = f"debugging_Json/{output_json_name}.json"
with open(json_file_path, "w", encoding="utf-8") as f:
json.dump(value, f, ensure_ascii=False, indent=4, default=lambda o: str(o))
■pathlib関連
■■pathlibでパスを通す
pathlibでパスを通す。親ディレクトリにもパスを通す。
from pathlib import Path
sys.path.append(str(Path(__file__).resolve().parent))
sys.path.append(str(Path(__file__).resolve().parents[4]))
sys.path.append(str(Path(__file__).resolve()))
import sys
print("\n".join(sys.path))
で確認
■■pathlibでパスを結合する
from pathlib import Path
out_path = "output.md"
dire = "out"
full_path = Path(dire) / out_path
print(full_path)
■入力されたPathがファイルなのかディレクトリなのかを判定
入力されたPathがファイルなのかディレクトリなのかを判定して、ディレクトリならばGlobで中身をリスト化
from pathlib import Path
def list_directory_contents(path_str):
path = Path(path_str)
if path.is_file():
print(f"{path} is a file.")
return path
elif path.is_dir():
print(f"{path} is a directory. Listing its contents:")
file_list = list(path.glob("*"))
for file in file_list:
print(f" - {file}")
return file_list
else:
print(f"{path} does not exist or is an invalid path.")
■タイムスタンプ
from datetime import datetime
# 現在時刻の取得して文字列にする
time_str = datetime.now().strftime('%Y-%m-%d_%H%M%S')
print(time_str)
# ファイル名への利用例
filename = f"output_{time_str}.txt"
最終更新:2026年04月27日 11:43