`诗运行黑myscript.py`和`黑myscript.py`有什么区别?

What is the difference between `poetry run black myscript.py` and `black myscript.py`?

基于poetry docs

Likewise if you have command line tools such as pytest or black you can run them using poetry run pytest

建议使用 black 的方法是:

poetry run black myscript.py

但是,如果我只是使用

,我没有发现任何行为差异
black myscript.py

这两种方法有什么区别?

它允许您 运行 black(或 run 之后的任何命令)安装在您的虚拟环境中 而无需先激活您的虚拟环境.

相关注释在 poetry run docs(强调我的):

The run command executes the given command inside the project’s virtualenv.

假设您有这个 poetry-demo 项目和 main.py,并且您安装了 black :

poetry-demo$ ls
README.rst     main.py        poetry.lock    poetry_demo    pyproject.toml tests

poetry-demo$ poetry add black
The following packages are already present in the pyproject.toml and will be skipped:

  • black

...

如果您没有先激活您的虚拟环境(即 poetry shell)并且 如果您没有在系统的其他任何地方安装 black,简单地做 black file.py 会失败:

poetry-demo$ which black

poetry-demo$ black main.py
-bash: black: command not found

但是,使用 poetry run,即使不激活您的虚拟环境,您也可以 运行 black:

poetry-demo$ poetry run black main.py
All done! ✨  ✨
1 file left unchanged.

你困惑的根源可能是因为你已经激活了你的虚拟环境,所以真的没有区别:

poetry-demo$ poetry shell
Spawning shell within /path/to/virtualenvs/poetry-demo-hCA44HQ0-py3.8
poetry-demo$ . /path/to/virtualenvs/poetry-demo-hCA44HQ0-py3.8/bin/activate

(poetry-demo-hCA44HQ0-py3.8) poetry-demo$ black main.py
All done! ✨  ✨
1 file left unchanged.

(poetry-demo-hCA44HQ0-py3.8) poetry-demo$ poetry run black main.py
All done! ✨  ✨
1 file left unchanged.