我有一个运行源代码的bash构建脚本,因此可以激活Python虚拟环境。我首先使用进行单元测试python3.7 -m unittest。但是,如果这些都失败了,我就不想运行主程序。因此,我需要停用虚拟环境(这样终端才能回到其原始状态),然后return 1退出构建脚本。
所以我的脚本看起来像这样
# activate virtual env ...
python3.7 -m unittest || deactivate; return 1;
python3.7 app.py
deactivate
Run Code Online (Sandbox Code Playgroud)
当单元测试失败时,python3.7 -m unittest将返回1并按预期停用虚拟环境。
当单元测试成功运行时,python3.7 -m unittest返回0,但是奇怪的是管道的右侧似乎在运行。我还没有弄清楚bash或bash是否很奇怪,deactivate但是这里有一些行为示例:
(exit 0) || deactivate; echo "Tests failed"; return 1; (Output: "Tests failed", deactivate not run)
(exit 0) || echo "Deactivating"; deactivate; echo "Tests failed"; return 1; (Output: "Tests failed", deactivate ran)
(exit 0) || echo "Tests failed"; return 1; (Output: Nothing, deactivate not run)
Run Code Online (Sandbox Code Playgroud)
这三个中的最后一个是有意义的,并且遵循预期的行为,其他两个则没有。
这与Bash Pitfall 22有关,但不完全相同。重要的是语句如何分组:
cmd1 || cmd2; cmd3
Run Code Online (Sandbox Code Playgroud)
将运行cmd1,并且如果退出状态为非零,则cmd2; 那么,不管是什么,cmd3。
目的是这样的:
cmd1 || { cmd2; cmd3; }
Run Code Online (Sandbox Code Playgroud)
如果cmd1失败,请运行cmd2和cmd3。
| 归档时间: |
|
| 查看次数: |
54 次 |
| 最近记录: |