C里import python模块出错,请帮忙看一下
是Programming python 3rd里的例子
usermod.py
[Copy to clipboard] [ - ]
CODE:
#########################################################
# C runs Python code in this module in embedded mode.
# Such a file can be changed without changing the C layer.
# There is just standard Python code (C does conversions).
# You can also run code in standard modules like string.
#########################################################
message = 'The meaning of life...'
def transform(input):
input = input.replace('life', 'Python')
return input.upper( )
embed-simple.c
[Copy to clipboard] [ - ]
CODE:
/*******************************************************
* simple code strings: C acts like the interactive
* prompt, code runs in _ _main_ _, no output sent to C;
*******************************************************/
#include <Python.h> /* standard API def */
#include <stdio.h>
main( ) {
printf("embed-simple\n");
Py_Initialize( );
PyRun_SimpleString("import os"); /* load .py file */
printf("pwd\n");
PyRun_SimpleString("os.system('pwd')"); /* print working directory */
PyRun_SimpleString("import usermod"); /* load .py file */
PyRun_SimpleString("print usermod.message"); /* on Python path */
PyRun_SimpleString("x = usermod.message"); /* compile and run */
PyRun_SimpleString("print usermod.transform(x)");
}
makefile.1
[Copy to clipboard] [ - ]
CODE:
# a Cygwin makefile that builds a C executable that embeds
# Python, assuming no external module libs must be linked in;
# uses Python header files, links in the Python lib file;
# both may be in other dirs (e.g., /usr) in your install;
PYLIB = /usr/bin
PYINC = /usr/include/python2.4
embed-simple: embed-simple.o
gcc embed-simple.o -L$(PYLIB) -lpython2.4 -g -o embed-simple
embed-simple.o: embed-simple.c
gcc embed-simple.c -c -g -I$(PYINC)
运行结果如下
[Copy to clipboard] [ - ]
CODE:
/Integrate/Embed/Basics$ ./embed-simple
embed-simple
pwd
/Integrate/Embed/Basics
Traceback (most recent call last):
File "<string>", line 1, in ?
ImportError: No module named usermod
Traceback (most recent call last):
File "<string>", line 1, in ?
NameError: name 'usermod' is not defined
Traceback (most recent call last):
File "<string>", line 1, in ?
NameError: name 'usermod' is not defined
Traceback (most recent call last):
File "<string>", line 1, in ?
NameError: name 'usermod' is not defined
但是在IDLE里面import usermod就可以。