首页 > 解决方案 > 错误:在 PATH 中找不到命令((来自 my_script)

问题描述

在使用 Pipenv 和 Pytest 处理 Python FastAPI 项目时,我被要求编写一个 Pipenv 脚本来运行测试。

项目结构如下:

.
├── app
|   ├── main.py
│   ├── my_package
│   │   ├── __init__.py
│   │   ├── (project folders)
│   │   └── tests
|   |       └── tests.py
│   └── __pycache__
└──(deployment scripts and folders, Pipfile, Dokerfile, etc)

我想从顶层结构(./app/.../tests.py)在 tests.py 上运行 Pytest。至少现在。

按照这里的建议,我目前从顶部运行它们:

( cd app ; python -m pytest my_package/tests/tests.py )

...按预期工作。

但是,当我添加我的 Pipfile-scripts-section 时:

[scripts]
my_script = "( cd app ; python -m pytest my_package/tests/tests.py )"

...运行它:

pipenv run my_script

我得到错误:

Error: the command ( (from my_script) could not be found within PATH.

我也试过:

[scripts]
my_script = "cd app && python -m pytest my_package/tests/tests.py"

...返回另一个类似的错误:

Error: the command cd (from my_script) could not be found within PATH.

所以很明显我把它用作 bash 别名是错误的。我已经尝试搜索有关 [scripts] 部分如何像我一样工作的更多文档,但我没有运气(还)。

标签: pythonbashpipenv

解决方案


我不熟悉您使用的工具,但错误消息表明它正在寻找可执行文件。(是 shell 语法的一部分,并且cd是内置的 shell,而不是可执行文件。尝试这个:

my_script = "bash -c 'cd app && python -m pytest my_package/tests/tests.py'"

bash是可执行文件,并-c使其运行您的代码段。

顺便说一句,请记住,这cd可能会失败,因此如果失败,脚本应该退出。


推荐阅读