首页 > 解决方案 > 如何从 Python 脚本调用 cmake 和命令?

问题描述

我有以下 Python 脚本。

代码

#!/usr/bin/env python3

import os

def Build(cmake_args):
    cmake cmake_args  # How to call cmake here by passing in the arguments?
    make install  # How to call make install here from within Python?

os.mkdir('build')
os.chdir('build')

# Call method Build by passing in all correct arguments
Build('-DCMAKE_INSTALL_PREFIX="./install" -DCMAKE_PREFIX_PATH="$PWD/../packages" ../SourceCodeFolder')

问题:
如何通过传入我理解cmake的所有 Cmake 参数来调用?CMakeLists.txt然后我怎么打电话make install

环境:
我在 macOS Catalina 上运行 Python 3.9.0。

PS:
我确保mkdir build && cd build && cmake -DCMAKE_INSTALL_PREFIX="./install" -DCMAKE_PREFIX_PATH="$PWD/../packages" ../SourceCodeFolder从 bash shell 运行时成功。因此,这只是如何从我的 Python 脚本调用 cmake 和 make 的问题

编辑:
我想在 Macos 和 Windows 上运行我的脚本。这就是从 Python 脚本运行 cmake 和 make 的原因。

标签: pythonpython-3.xcmake

解决方案


您可以使用subprocess.run(["command", "-arg"])

(来自https://docs.python.org/3.8/library/subprocess.html#subprocess.run


推荐阅读