Skip to content

How to run Python scripts


runコマンドは、inline metadataを使用したPythonスクリプトの実行をサポートしており、必要な依存関係と正しいバージョンのPythonを使用して専用のenvironmentが自動的に作成されます。

スクリプト・メタデータ・ブロックは、#scriptで始まり#///で終わるコメント・ブロックです。これら2行の間のすべての行は、#で始まり、コメント文字が削除されたときにTOMLドキュメントを含むコメント行である必要があります。

最上位のフィールドは次のとおりです。:

  • dependencies: スクリプトの実行時の依存関係を指定する文字列のリスト。各エントリは有効な依存関係指定子である必要があります。
  • requires-python: スクリプトと互換性のあるPythonバージョンを指定する文字列。このフィールドの値は、有効なバージョン指定子である必要があります。

次に、有効なメタデータブロックを持つPythonスクリプトの例を示します。:

# /// script
# requires-python = ">=3.11"
# dependencies = [
#   "httpx",
#   "rich",
# ]
# ///

import httpx
from rich.pretty import pprint

resp = httpx.get("https://peps.python.org/api/peps.json")
data = resp.json()
pprint([(k, v["title"]) for k, v in data.items()][:10])

直接実行するには:

$ hatch run /path/to/script.py
Creating environment: SyB4bPbL
Checking dependencies
Syncing dependencies
[
│   ('1', 'PEP Purpose and Guidelines'),
│   ('2', 'Procedure for Adding New Modules'),
│   ('3', 'Guidelines for Handling Bug Reports'),
│   ('4', 'Deprecation of Standard Modules'),
│   ('5', 'Guidelines for Language Evolution'),
│   ('6', 'Bug Fix Releases'),
│   ('7', 'Style Guide for C Code'),
│   ('8', 'Style Guide for Python Code'),
│   ('9', 'Sample Plaintext PEP Template'),
│   ('10', 'Voting Guidelines')
]

notes

  • この例の情報テキストは、最初の実行時に端末に一時的に表示されるだけです。
  • 環境名はスクリプトの絶対パスに基づいていますが、コマンドライン引数は絶対パスである必要はありません。

Environment configuration

[tool.hatch]テーブルを直接使用して、スクリプトのenvironmentを制御できます。たとえば、UV(スクリプトではデフォルトでenabled)を無効にする場合は、次のように追加できます。:

# /// script
# ...
# [tool.hatch]
# installer = "pip"
# ///