Jump to content
  • Advertisement
Sign in to follow this  
racnil

[C++/Python]Cannot Import Python Modules From C++

This topic is 2893 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello,
I'm considering using Python as the scripting language and want to import Python modules in C++ program. But now I have a problem importing python module in C++.
My OS is Linux, OpenSUSE 11.3. Using g++ compiler
My source code is from the official website of Python: http://docs.python.org/extending/embedding.html#pure-embedding
Compiling... very smooth (with linker: -Xlinker -export-dynamic). But when the program runs, it just cannot find my module. But it CAN find "os" and "sys" module. That means, C++ has not treat its own directory as the module path. But how can man solve it?

Share this post


Link to post
Share on other sites
Advertisement

Check to see if . is in sys.path. If it isn't then have your program add it.


Thank you for your reply!
No, it isn't. But how to add it? I've tried Py_SetProgramName(argv[0]);
But it doesn't work...

Share this post


Link to post
Share on other sites
The simplest (though not the most efficient method) would be to add:

PyRun_SimpleString("sys.path.append(\".\")");

to your program sometime before you try importing modules.

Share this post


Link to post
Share on other sites

The simplest (though not the most efficient method) would be to add:

PyRun_SimpleString("sys.path.append(\".\")");

to your program sometime before you try importing modules.


OH MY GOD it works!! :o :o :o :lol: :lol: :lol:
I've thought the "PyRun_SimpleString()" is just a “disposable” function, when it runs, it has no effect on the next run...
So it works until Py_Finalize()...

The problem is solved, and thank you very very much!!!


p.s. PyRun_SimpleString("import sys"); before append ^_^

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!