【发布时间】:2017-12-22 14:05:51
【问题描述】:
我需要在 Windows 平台下从我的 C++ 项目中调用实现为 Python (3.6) 函数的管道。文件“experiment_test.py”中的函数“function_name”将文本字符串作为输入参数,并返回另一个文本字符串作为结果。我尝试了下面的代码,但它不能正常工作——来自库 shutil、codecs、makedirs 等的 python 函数不起作用。
C++ 代码(精简):
std::string Text,Result;
PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pValue;
Py_Initialize();
pName = PyUnicode_FromString("experiment_test");
pModule = PyImport_Import(pName);
pDict = PyModule_GetDict(pModule);
pFunc = PyDict_GetItemString(pDict, "function_name");
pArgs = PyTuple_New(1);
pValue = PyUnicode_FromString(Text.c_str());
PyTuple_SetItem(pArgs, 0, pValue);
if (PyCallable_Check(pFunc))
{
pValue = PyObject_CallObject(pFunc, pArgs);
if (pValue != NULL)
{
Result = PyUnicode_AsUTF8(pValue);
Py_DECREF(pValue);
}
else return false;
}
// ...
Py_Finalize();
Python 代码(精简):
#!/usr/local/bin/python3
import shutil
import codecs
from os import makedirs
from os import path
from os import unlink
from subprocess import call
def function_name():
name = 'working_files/current_text'
if not path.exists('working_files'):
makedirs('working_files')
if path.exists('result.txt'):
unlink('result.txt')
with codecs.open(name + '.txt', 'w', encoding='utf-8') as f:
f.write(text)
# ...
return result
因此 Python 不会生成新文件。我尝试通过在 Py_Initialize(); 之后调用 PyRun_SimpleString("import shutil"); 等在 C++ 中导入 Python 模块,但它没有帮助。
我做错了什么?
【问题讨论】:
-
什么确切不起作用(错误、回溯等)?您是否尝试过直接运行 Python 模块(不添加 C++ 层)?请注意,您的代码在语法上不正确(缩进)。
-
shutil、编解码器、makedirs 中的 Python 函数在从 C++ 调用“function_name”时不起作用。如果我从命令行调用 Python 模块,它可以正常工作。没有错误发生 - C++ 接收到等于输入的结果。 Python 函数应将输入字符串写入文本文件,处理此文件,然后读取结果并将其返回。我的代码中的缩进是正确的,不幸的是我在这里写的时候出错了,谢谢。