Python SyntaxError when embedding in C

烈酒焚心 提交于 2019-12-11 20:42:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!