How to Use Python script code in C ++

Source: Internet
Author: User

Python script code needs to be mixed with many languages. Among them, C ++ is quite a lot. Let's take a look at how to smoothly use Python script code in C ++. I hope you can find your answers in this article.

To embed Python script code in c ++, except for writing the script engine by yourself, lua and python can be used in c ++. In addition, MonoBind, angelScript library is a number of c ++ script libraries that can be embedded in c ++ for use.

Today, we have attempted to embed Python script code in c ++ (the sample code is in Python-2.5.2 \ Demo \ embed)

 
 
  1. #include <Python.h> 
  2. int main(int argc, char *argv[])  
  3. {  
  4. // Py_NoSiteFlag = 1;  
  5. // Py_SetPythonHome("D:\\usr\\Python"); // PYTHONHOME  
  6. Py_Initialize();  
  7. PyRun_SimpleString("from time import time,ctime\n"  
  8. "print 'Today is',ctime(time())\n");  
  9. Py_Finalize();  
  10. return 0;  

During runtime, errors similar to 'import site' failed; use-v for traceback may occur because of the path problem during python import module. there are three ways to solve the problem (previously, setting the environment variable PYTHONPATH seems to be invalid in 2.5 ).

0. uncomment Py_NoSiteFlag = 1;

This is just to cancel the import site. Of course, if you want to import anything in the code, an error will still occur.

A. Set the environment variable PYTHONHOME = D: \ usr \ Python

B. Call the function before calling Py_Initialize.

Py_SetPythonHome ("D :\\ usr \ Python"); // The parameter is the python installation directory.

The above is how to use Python script code in C ++. I hope you will have some gains.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.