如果C++代码不是动态生成的或者类似的情况,我建议您在启动Python程序之前先构建它,然后仅从Python程序中执行它。
如果您有一个很好的理由需要从Python代码中构建它,我在
https://github.com/kyotov/experiments为您创建了一个小例子。如下所示的内容适用于run_experiements.py:
import os
import subprocess
def main():
os.makedirs('build', exist_ok=True)
subprocess.check_call('cmake -B build -G "NMake Makefiles"', shell=True)
subprocess.check_call('cmake --build .', shell=True, cwd='build')
subprocess.check_call('experiments 1 2 3', shell=True, cwd='build')
subprocess.check_call('experiments 2 3 4', shell=True, cwd='build')
if __name__ == '__main__':
main()
我使用以下内容作为
main.cpp
:
#include <iostream>
int main(int argc, char **argv) {
for (auto i = 0; i < argc; i++)
std::cout << argv[i] << std::endl;
return 0;
}
当我运行python run_experiements.py
时,我会得到以下输出:
(base) C:\kamen\clion\experiments>python run_experiments.py
-- Configuring done
-- Generating done
-- Build files have been written to: C:/kamen/clion/experiments/build
[100%] Built target experiments
experiments
1
2
3
experiments
2
3
4
为了使其正常工作,您需要正确设置环境以找到所需的工具。在我的情况下,我使用Miniconda3进行Python开发,然后使用"
"C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Auxiliary\Build\vcvars64.bat"
"将编译器和cmake添加至路径中。
如果您没有Linux机器,但是如果您将
-G
设为条件并使用
Unix Makefiles
,它也可能在Linux(以及其他地方)上运行。请注意,在Windows上,您不必担心
.exe
,因为即使您没有指定它,shell也足够聪明,会自动启动程序。
cmake --build
可以帮助您避免一些特定于平台的二进制文件,例如make
。而且,您可以使用类似os.mkdir
的东西来避免调用某些特定于操作系统的命令。您可能仍然需要一个子进程来调用cmake
,对此我建议使用subprocess
模块而不是os.system
。 - 0x5453CMakeLists.txt
包含一个名为 run 的可执行目标,否则您需要使用该可执行文件的名称来运行它。而这个名称肯定是 与平台相关 的(在 Windows 上具有.exe
扩展名,在 Linux 上没有扩展名)。 - Tsyvarev