我正在使用 Docker 容器进行本地 Web 开发。我有一个 bash 脚本,用于在 Docker 容器内的 pipenv 环境中运行 Django 的 manage.py test
、flake8
和 coverage html
。
一个简单的版本是:
#!/bin/bash
set -e
docker exec hines_web /bin/sh -c "pipenv run coverage run --source=. manage.py test ; pipenv run flake8 ; pipenv run coverage html"
这有效。但是,因为每个命令必须单独使用 pipenv run
,所以它比它需要的要慢。
有没有办法在单个 pipenv run
之后将多个命令链接在一起,或者将多个命令发送到 pipenv shell
中以便它们运行?
(任何关于改进一般方法的想法都表示赞赏!)
答案 0 :(得分:0)
这是我的解决方法,它费力到让我觉得我完全错误地处理了这个问题,但它有效。三步:
1. 将运行我们的命令的 shell 脚本。这旨在在 pipenv 环境中运行。这是scripts/pipenv-run-tests.sh
:
#!/bin/sh
set -e
# Runs the Django test suite, flake8, and generates HTML coverage reports.
# This script is called by using the shortcut defined in Pipfile:
# pipenv run tests
# You can optionally pass in a test, or test module or class, as an argument, e.g.
# ./pipenv-run-tests.sh tests.appname.test_models.TestClass.test_a_thing
TESTS_TO_RUN=${1:-tests}
coverage run --source=. ./manage.py test $TESTS_TO_RUN
flake8
coverage html
2.我们在 Pipfile
中定义了一个 Custom Script Shortcut:
[scripts]
tests = "./scripts/pipenv-run-tests.sh"
这意味着,如果我们登录到 Docker 容器上的 shell,我们可以执行以下操作:pipenv run tests
和我们的 scripts/pipenv-run-tests.sh
将在 pipenv 环境中运行。 pipenv run tests
之后包含的任何参数都会传递给脚本。
3. 最后,我们设计了一个从主机运行的脚本,它在 Docker 中运行我们的自定义脚本快捷方式。这是scripts/run-tests.sh
:
#!/bin/bash
set -e
# Call this from the host machine.
# It will call the `tests` shortcut defined in Pipfile, which will run
# a script within the pipenv environment.
# You can optionally pass in a test, or test module or class, as an argument, e.g.
# ./run-tests.sh tests.appname.test_models.TestClass.test_a_thing
TESTS_TO_RUN=${1:-tests}
docker exec hines_web /bin/sh -c "pipenv run tests $TESTS_TO_RUN"
现在,在主机上,我们可以执行以下操作:./scripts/run-tests.sh
,这将在 Docker 容器内调用 pipenv 快捷方式,该快捷方式将运行 scripts/pipenv-run-tests.sh
脚本。提供的任何参数都会传递到最终脚本。
(请注意,上面的 hines_web
是我的 docker-compose.yml
中定义的 Docker 容器的名称。)