0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonでよく使うコード

Last updated at Posted at 2024-09-27

vscode の python 設定

  • pythonの拡張機能が入っていることが前提です。
~/.vscode/settings.json
{
    "python.analysis.extraPaths": [
        //Djangoライブラリの格納ディレクトリ
        "/Users/user_name/.pyenv/versions/3.9.0/lib/python3.9/site-packages",        
        //プロジェクトのルートディレクトリ
        "/Users/user_name/workspace/project_name",
    ]
}

pyコマンドでVersion切り替え

// バージョン一覧を表示
C:\Users\J\Desktop>py -0p
 -V:3.13          C:\Users\J\AppData\Local\Programs\Python\Python313\python.exe
 -V:3.12 *        C:\Users\J\AppData\Local\Programs\Python\Python312\python.exe

//3.13を指定して実行
# py -3.13 main.py

デフォルトのpython Versionを変更する方法
  1. 環境変数を開く
  2. システム環境変数の新規ボタンをクリック(下の環境変数)
  3. 変数名:PY_PYTHON
  4. 値:3.12
  5. 以上

例外の詳細情報を取得

# 例外を一旦受け取って再送しているファイルを想定
import sys

try:
    result = 1 / 0  # ZeroDivisionErrorが起きる
except Exception as e:
    exception_type, exception_object, exception_traceback = sys.exc_info()
    filename = exception_traceback.tb_frame.f_code.co_filename
    line_no = exception_traceback.tb_lineno
    raise Exception(f"{filname}{line_no}行目でエラーが発生しました。詳細:{e}")

logging

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

format = "%(asctime)s %(levelname)-9s [%(filename)s:%(lineno)d] %(message)s"

st_handler = logging.StreamHandler()
st_handler.setLevel(logging.DEBUG)
# StreamHandlerによる出力フォーマットを先で定義した'format'に設定
st_handler.setFormatter(logging.Formatter(format))

fl_handler = logging.FileHandler(filename="sample9.log", encoding="utf-8")
fl_handler.setLevel(logging.WARNING)
# FileHandlerによる出力フォーマットを先で定義した'format'に設定
fl_handler.setFormatter(logging.Formatter(format))

logger.addHandler(st_handler)
logger.addHandler(fl_handler)

logger.info("I am info log.")
logger.warning("I am warning log.")

Selenium-Select

from selenium.webdriver.support.select import Select

select_element = d.find_element(By.NAME, 'selectomatic')
select = Select(select_element)

select.select_by_value('two')
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?