好的,这是Python网站上的基本示例,用于简单的runpy.exe
在下面运行Python脚本。在引用Python包含文件并链接到python35.lib
以获得基本功能后,在x64 Windows上使用Visual Studio 2015可以正常工作(文档中未提及pyvenv.cfg
必须在EXE目录中)。但是,仅在使用嵌入式NumPy
时,调用导入ImportError: No module named 'numpy' Failed to load "eig"
的脚本会导致此错误python35.zip
,那么如何在嵌入式Python EXE中包含NumPy
?即我还想“嵌入” NumPy(作为.zip,目录,.dll或.pyd等)。我尝试添加NumPy包含项,并且还链接到npymath.lib
,但是遇到相同的导入错误。我还研究了一些Cython包装器代码,但没有找到解决方案。这是Python嵌入式示例代码:
#include <Python.h>
#include <iostream>
int main(int argc, char *argv[])
{
PyObject *pName, *pModule, *pDict, *pFunc;
PyObject *pArgs, *pValue;
int i;
if (argc < 3) {
fprintf(stderr, "Usage: runpy pythonfile funcname [args]\n");
return 1;
}
Py_SetPath(L"python35.zip"); //this is in the current directory
Py_Initialize();
pName = PyUnicode_DecodeFSDefault(argv[1]);
/* Error checking of pName left out */
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule != NULL) {
pFunc = PyObject_GetAttrString(pModule, argv[2]);
/* pFunc is a new reference */
if (pFunc && PyCallable_Check(pFunc)) {
pArgs = PyTuple_New(argc - 3);
for (i = 0; i < argc - 3; ++i) {
pValue = PyLong_FromLong(atoi(argv[i + 3]));
if (!pValue) {
Py_DECREF(pArgs);
Py_DECREF(pModule);
fprintf(stderr, "Cannot convert argument\n");
return 1;
}
/* pValue reference stolen here: */
PyTuple_SetItem(pArgs, i, pValue);
}
pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
if (pValue != NULL) {
printf("Result of call: %ld\n", PyLong_AsLong(pValue));
Py_DECREF(pValue);
}
else {
Py_DECREF(pFunc);
Py_DECREF(pModule);
PyErr_Print();
fprintf(stderr, "Call failed\n");
return 1;
}
}
else {
if (PyErr_Occurred())
PyErr_Print();
fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
}
Py_XDECREF(pFunc);
Py_DECREF(pModule);
}
else {
PyErr_Print();
fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
return 1;
}
Py_Finalize();
return 0;
}
嵌入文件在此处:存档内的https://www.python.org/ftp/python/3.5.2/python-3.5.2-embed-amd64.zip,
python35.zip
。这是简单的测试脚本(要测试的runpy eig eig 10
-请注意,如果您不嵌入Python35.zip
并安装了NumPy
/ SciPy
,它将运行):eig.py
import numpy as np
from scipy import linalg
def eig(a):
c = np.random.rand(a,a)*100
c = np.corrcoef(c)
print('You are taking the eigsh of a ', a, '^2 matrix')
e, f = linalg.eig(c)
return print('Eigvals are: ',np.diag(f))
有人知道如何解决此问题吗?非常感激。
更新:这是带有英特尔MKL的x64 Python 3.5 Windows NumPy SciPy和Pandas的编译版本:https://www.dropbox.com/sh/2smbgen2i9ilf2e/AADI8A3pCAFU-EqNLTbOiUwJa?dl=0
最佳答案
这不起作用,因为numpy不在zipfile python35.zip
中。
runpy程序将路径设置为python35.zip
:因此,这是该程序异常在Pythonpath中的唯一路径...
您还必须将本地numpy-folder的父文件夹添加到Pythonpath中,以使其正常工作。
关于c++ - 嵌入式Python无法使用NumPy指向Python35.zip-如何修复?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38333320/