关于嵌入python的问题

wjh1014 2004-12-01 09:36:26
Programming Python, 2nd Edition上的例子

usermod.py 文件

import string

message = 'The meaning of life...'

def transform(input):
input = string.replace(input, 'life', 'Python')
return string.upper(input)

embed-object.c

#include <Python.h>

main( ) {
char *cstr;
PyObject *pstr, *pmod, *pfunc, *pargs;
printf("embed-object\n");
Py_Initialize( );

/* get usermod.message */
pmod = PyImport_ImportModule("usermod");
pstr = PyObject_GetAttrString(pmod, "message");

/* convert string to C */
PyArg_Parse(pstr, "s", &cstr);
printf("%s\n", cstr);
Py_DECREF(pstr);

/* call usermod.transform(usermod.message) */
pfunc = PyObject_GetAttrString(pmod, "transform");
pargs = Py_BuildValue("(s)", cstr);
pstr = PyEval_CallObject(pfunc, pargs);
PyArg_Parse(pstr, "s", &cstr);
printf("%s\n", cstr);

/* free owned objects */
Py_DECREF(pmod);
Py_DECREF(pstr);
Py_DECREF(pfunc); /* not really needed in main( ) */
Py_DECREF(pargs); /* since all memory goes away */
}

不知为什么PyImport_ImportModule总返回为NULL,但如果PyImport_ImportModule("math")就能成功。


...全文
137 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
wjh1014 2004-12-08
  • 打赏
  • 举报
回复
多谢xyzxyz1111(如是我闻)
我重新装了个python2。4,可以了
wjh1014 2004-12-02
  • 打赏
  • 举报
回复
都放在同一个文件夹下面,并且执行 pmod = PyImport_ImportModule("usermod");时生成了usermod.pyc文件,但pmod为NULL啊
xyzxyz1111 2004-12-02
  • 打赏
  • 举报
回复
我运行了一遍,发现并没有成为NULL,一切正常牙。
你用的是Debug还是Release?我用的是Release
python 2.3.3
VC 6.0
编意完后把Release目录下的可执行文件放到usermod同目下,然后执行第。
xyzxyz1111 2004-12-01
  • 打赏
  • 举报
回复
usermod.py 和可执行文件的路径个是什么?

37,719

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧