0

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"

2 Answers 2

1

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

1

You're running the executable as Python code, which it is not. Verify the arguments to fopen() and PyRun_SimpleFileExFlags().

5 Comments

Hello Ignacio. Thanks for your answer. Can you please explain your answer a bit? I couldn't understand what you said.
Do you understand what argv is?
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.
"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.
Ohh, I got it. Thanks Ignacio. Now, I call fopen like fopen(argv[1],"r") and my code works as it should. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.