在C++ PyBind11中从其他Python文件导入Python文件(模块

c8ib6hqw  于 2023-02-18  发布在  Python
关注(0)|答案(1)|浏览(198)

好吧。既然我在Github上的问题没有得到正确的回答,我被建议去一个合适的论坛,我在这里。我试图从另一个嵌入了PyBind11的Python文件导入一个Python文件。问题是这样的:
我有两个文件:* 峰面积 *:

def add(a, b):
    return a + b

main.py

print('Hello, world!')

我有我的C++代码:

py::initialize_interpreter(); // I am purposely not using eval_file because in the future I might not be using files, but strings instead.
py::exec(readFile("mts.py"));
py::exec(readFile("main.py"));
py::finalize_interpreter();

我的问题是,如何在'main.py'中导入'mts.py'?例如,如何在'main.py'中调用'add'?

rsl1atfo

rsl1atfo1#

从逻辑上讲,您可以从www.example.com调用它main.py,例如 main.py

# I import the function "add ()" from the file (be sure to prescribe the full path from the executive file *.exe or ./*)
# It is important for a built -in interpreter to register a full path from a executable file for PYBIND11
# Simple file hierarchy
# -dir-
#   |-main.cpp
#   |-main.exe or main (Executable)
#   |-scripts
#       |-mnt.py
#       |-main.py
from scripts.mnt import add

# if file hierarchy is such
# -dir-
#   |-main.cpp
#   |-main.exe or main (Executable)
#   |-mnt.py
#   |-main.py
from mnt import add

# call function example
add ( 4, 4 ) # 8

希望我帮你解决了问题。

相关问题