问题
I have a python file which runs fine when I execute it against my python interpreter.
I'm trying to call the same file from a C program using the python C API:
#include <Python.h>
#include <stdio.h>
int main(int argc, char* argv[]){
FILE* fp;
Py_SetProgramName(argv[0]);
Py_Initialize();
PySys_SetArgv(argc, argv);
fp = fopen("floatcli.py", "r");
PyRun_SimpleFile(fp, "floatcli.py");
Py_Finalize();
}
However, when I run this I get a python syntax error:
File "floatcli.py", line 1
üBa
^
SyntaxError: invalid syntax
(there is also a load of ? in boxes surrounding the üBa which isn't shown here).
The first line of floatcli.py
is just an import statement...any idea what is going on?
回答1:
Do a hex dump of your Python file, it's probably encoded in one of the Unicode formats and what you're seeing may be the header indicating that encoding.
If it is, you have two options. The first is to convert it to ASCII so your embedded Python interpreter can read it, or find out how to modify your embedded Python interpreter to handle the encoding.
来源:https://stackoverflow.com/questions/26860783/python-syntaxerror-when-embedding-in-c