问题描述
我希望能够从 JetBrains CLion 中特定运行/调试配置中的文件中获取一个或多个环境变量。 据我所知,在撰写本文时,这个特定问题 has not been answered on Stack Overflow。我认为它应该对其他 JetBrains IDE 的用户有用。
主要来自 Python 背景,我大量使用 Python dotenv 库在文件中定义多个环境变量。 这些文件中的语法看起来像
VARIABLE_NAME=value
这看起来类似于我在 shell 脚本中定义(局部)变量的方式。
我过去使用过的其他语言的模块(例如 Julia、Node)或内置功能(例如 R)都遵循此 { {1}} 语法。 我希望从 IDE 中的文件中获取环境变量应该有类似的感觉。
要么 CLion 没有,我只是不知道,要么我偶然发现了配置错误(更有可能)或错误(不太可能)。
这个问题不是什么
我不想set CMake variables。我想通过 VARIABLE=value
将环境变量设置为对我的程序可见。
answer on a related question 推荐与 CLion 不兼容的 a plugin。此外,CLion 已经内置了对运行/调试配置中的源环境文件的支持,因此不需要插件。
我尝试了什么
最小工作示例
std::getenv
这里是#include <iostream>
int main() {
auto test_val = getenv("TEST");
std::cout << "TEST value: " << test_val << std::endl;
}
的内容:
/home/alan/Documents/20201222-clion-env-file-test/env
(我试过有和没有换行符,但没有任何区别。)
损坏的运行/调试配置
预期输出TEST=hello
实际产量
/home/alan/Documents/20201222-clion-env-file-test/cmake-build-debug/20201222_clion_env_file_test
TEST value: hello
Process finished with exit code 0
工作运行/调试配置
显式定义变量有效:
预期输出/home/alan/Documents/20201222-clion-env-file-test/cmake-build-debug/20201222_clion_env_file_test
TEST value:
Process finished with exit code 0
实际产量
/home/alan/Documents/20201222-clion-env-file-test/cmake-build-debug/20201222_clion_env_file_test
TEST value: hi
Process finished with exit code 0
tl;博士
如果我从文件中设置环境变量,为什么 CLion 不选择它们?
系统信息
/home/alan/Documents/20201222-clion-env-file-test/cmake-build-debug/20201222_clion_env_file_test
TEST value: hi
Process finished with exit code 0
解决方法
CLion 没有遵循预期的语法,但 documentation 没有明确说明:
使用从文件加载变量字段将 CLion 指向配置环境的脚本。
线索是script这个词。如果您希望环境变量在脚本之外可用,则需要 CLion 2020.3
Build #CL-203.5981.166,built on December 1,2020
...
Runtime version: 11.0.9+11-b1145.21 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o.
Linux 5.8.0-7630-generic
它,就像在 shell 中一样:
export
进行必要的更改会得到预期的结果:
alan@just-testing:~/Documents/20201222-clion-env-file-test$ cat ./env
TEST=hello
alan@just-testing:~/Documents/20201222-clion-env-file-test$ source ./env && ./cmake-build-debug/20201222_clion_env_file_test
TEST value: alan@just-testing:~/Documents/20201222-clion-env-file-test$
以下是进行此更改后 CLion 的输出:
alan@just-testing:~/Documents/20201222-clion-env-file-test$ cat env
export TEST=hello
alan@just-testing:~/Documents/20201222-clion-env-file-test$ source ./env && ./cmake-build-debug/20201222_clion_env_file_test
TEST value: hello
如果您最近有任何 C/C++ 经验,这可能很明显,但如果您像我一样使用 /home/alan/Documents/20201222-clion-env-file-test/cmake-build-debug/20201222_clion_env_file_test
TEST value: hello
Process finished with exit code 0
语法想到解释型语言,这绝对不明显。