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

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

在使用 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) 运行 Pytest on tests.py。至少现在。

根据建议 here,我目前 运行 他们从顶部开始:

( 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"

... returns 另一个类似的错误:

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

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

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

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

此处 bash 是可执行文件,-c 使其成为 运行 您的代码段。

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