Skip to content

How to run Python scriptsPythonスクリプトの実行方法


The run command supports executing Python scripts with inline metadata, such that a dedicated environment is automatically created with the required dependencies and with the correct version of Python.このrunコマンドは、インラインメタデータを使用してPythonスクリプトを実行することをサポートしており、必要な依存関係と正しいPythonのバージョンを持つ専用の環境が自動的に作成されます。

A script metadata block is a comment block that starts with # /// script and ends with # ///. Every line between those two lines must be a comment line that starts with # and contains a TOML document when the comment characters are removed.スクリプトメタデータブロックは、# /// scriptで始まり、# ///で終わるコメントブロックです。これらの2行の間のすべての行は、#で始まるコメント行でなければならず、コメント文字が削除されるとTOMLドキュメントを含む必要があります。

The top-level fields are:トップレベルのフィールドは次のとおりです:

  • dependencies: A list of strings that specifies the runtime dependencies of the script. Each entry must be a valid dependency specifier.dependencies: スクリプトのランタイム依存関係を指定する文字列のリスト。各エントリは有効な依存関係指定子でなければなりません。
  • requires-python: A string that specifies the Python version(s) with which the script is compatible. The value of this field must be a valid version specifier.requires-python: スクリプトが互換性のあるPythonバージョンを指定する文字列。このフィールドの値は有効なバージョン指定子でなければなりません。

The following is an example of Python script with a valid metadata block:以下は、有効なメタデータブロックを持つ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])

Run it directly:直接実行します:

$ 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ノート

  • The informational text in this example is only temporarily shown in your terminal on the first run.この例の情報テキストは、最初の実行時に一時的にターミナルに表示されます。
  • Although the environment name is based on the script's absolute path, the command line argument does not have to be.環境名はスクリプトの絶対パスに基づいていますが、コマンドライン引数はそれに従う必要はありません。

Environment configuration環境設定

You may use the [tool.hatch] table directly to control the script's environment. For example, if you wanted to disable UV (which is enabled by default for scripts), you could add the following:スクリプトの環境を制御するために、[tool.hatch]テーブルを直接使用することができます。たとえば、UVを無効にしたい場合(これはスクリプトに対してデフォルトで有効です)、次のように追加できます:

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