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"
asked May 2, 2018 at 8:53
Abhishek Arya
5201 gold badge5 silver badges17 bronze badges
2 Answers 2
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.
Sign up to request clarification or add additional context in comments.
Comments
You're running the executable as Python code, which it is not. Verify the arguments to fopen() and PyRun_SimpleFileExFlags().
answered May 2, 2018 at 8:58
Ignacio Vazquez-Abrams
804k160 gold badges1.4k silver badges1.4k bronze badges
5 Comments
Abhishek Arya
Hello Ignacio. Thanks for your answer. Can you please explain your answer a bit? I couldn't understand what you said.
Ignacio Vazquez-Abrams
Do you understand what
argv is?Abhishek Arya
This is the way I'm running my cpp code
./cppPython cppPython.py. Basically, argv is the array containing the arguments that I pass to my c++ code.Ignacio Vazquez-Abrams
"argv is the array containing the arguments that I pass to my c++ code" Incorrect. It is all words parsed from the command line, not just the arguments.
Abhishek Arya
Ohh, I got it. Thanks Ignacio. Now, I call fopen like
fopen(argv[1],"r") and my code works as it should. Thanks again.default