嵌入python模块错误
所以我有 ac 到 python 包装器,它接受输入字符串并将它们传递给 python 函数。我收到的错误是 python API 无法识别我的 python 文件...
PyObject *pName, *pModule, *pFunc;
QString pyFile="Test.py";
Py_Initialize();
pName = PyUnicode_FromString(pyFile.toAscii().data());
pModule = PyImport_Import(pName);
错误是“ImportError:没有名为 Test.py 的模块” 这是当我将 Test.py 放在与我的项目相同的目录中时
,当我将 Test.py 放在目录树中的上一层时,出现了另一个错误 错误是“不支持按文件名导入”,
所以我猜绝对路径不起作用?但在我的示例中的第一种情况下,我明确地将 Test.py 放在与我的项目相同的目录中,为什么我会收到错误? 蟒蛇代码是:
import sys
import os
def printFileClass(fileName, className):
print ("The OMC CORBA File name is ", fileName,"\n")
print ("The selected Modelica Class is ", className)
return ("Done operations")
def main():
print ("Hello! Here is testing script's main \n")
if __name__=='__main__':
main()
So i have a c to python wrapper that takes input strings and pass them to a python function. the error im getting is that the python API is not recognizing my python file...
PyObject *pName, *pModule, *pFunc;
QString pyFile="Test.py";
Py_Initialize();
pName = PyUnicode_FromString(pyFile.toAscii().data());
pModule = PyImport_Import(pName);
error is "ImportError: No module named Test.py"
This is when i have my Test.py in the same directory as my project
when i placed my Test.py up one level in my directory tree, another error came up
error is "Import by filename is not supported"
so i guess absolute paths dont work? but in the first case in my example, i clearly placed my Test.py in the same directory as my project, why am i getting the error?
python code is:
import sys
import os
def printFileClass(fileName, className):
print ("The OMC CORBA File name is ", fileName,"\n")
print ("The selected Modelica Class is ", className)
return ("Done operations")
def main():
print ("Hello! Here is testing script's main \n")
if __name__=='__main__':
main()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
PYTHONPATH 环境变量可用于解决您的问题。
在代码中,您可以在 Py_Initialize() 之前的某个位置执行此操作:
第三个参数 0 表示覆盖 - 它为零,因此您也可以从 shell 传递 PYTHONPATH。如果您想始终使用您编码的路径,可以将其设置为 1。
我不确定这不会给您带来其他问题,但对于简单的测试来说它是有效的。
另外,请勿在传递给 PyImport_Import 的模块名称中包含 .py 扩展名。
我在 Linux 系统上对此进行了测试。
The PYTHONPATH environment variable can be used to fix your problem.
In your code, you can do this somewhere before Py_Initialize():
The third parameter, 0, means overwrite - it's zero so you can also pass PYTHONPATH from the shell. If you want to always use a path that you coded, you can set that to 1.
I'm not sure this doesn't expose you to other problems, but for a simple test it works.
Also, don't include the .py extension in the module name you pass to PyImport_Import.
I tested this on a Linux system.
在第一种情况下确实没有名为“Test.py”的模块。您的模块在文件“Test.py”中被命名为“Test”。尝试导入它。 “Test.py”将是名为“Test”的包中的“py”子模块。
It's true in the first case there is no module named "Test.py". Your module, in the file "Test.py", is named "Test". Try importing that. "Test.py" would be the "py" submodule in a package named "Test."