Search code examples
pythonc++python-embedding

Encoding for embedding python in C++


I'm trying to embed a python code in C++ and it compiles successfully but when I try to run my code, I get the following error.

File "./cppPython", line 1
SyntaxError: Non-ASCII character '\x88' in file ./cppPython on line 2, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

These are my C++ and Python codes.

CPP code

#include <Python.h>
#include <iostream>

using namespace std;
int main(int argc, char *argv[])
{ 
  FILE *fp = fopen(argv[0],"r");
  Py_SetProgramName(argv[0]);  /* optional but recommended */
  Py_Initialize();

  PyRun_SimpleFileExFlags(fp,argv[0],0,NULL);

  Py_Finalize();
  return 0;
}

Python code

#!/usr/bin/env python
# -*- coding: utf-8 -*-
print "hello"

Solution

  • argv[0] gives the C++ executable name. For eg. If you named the C++ executable as abc and executed as:

    ./abc pythonFileName.py

    Then the argv array will have argv[0] as ./abc and argv[1] as pythonFileName.py.

    So, please use the index 1.