对于我在计算机科学领域的高级项目,我正在制作一个益智视频游戏,它将教人们如何使用Python进行编码。设计的最大部分涉及创建吸引用户的拼图,用户可以对其进行分类。但是,拼图设计不是我当前遇到的问题。
虽然我最初的想法是让每个“问题”都有一系列预期的答案来检查用户的答案,但我学校的CS部门负责人(主持高级研讨会)建议我改用嵌入式Python,但他建议同时挑战我,并且为了使数据更容易嵌入简单的解释器,该解释器将对照预期输出检查用户代码输出。
快进了四个星期,我已经学到了很多有关Python实际工作方式的知识。只要C字符串中没有空格,我什至可以将解释器转换为简单的C字符串作为python代码,例如print(“ hello”)或print(“ hello / tworld”)之类的东西。
该代码看起来像
#include "pch.h"
#include <iostream>
#include <string>
#include <fstream>
#include <Python.h>
void exec_pycode(const char* code);
int main()
{
using namespace std;
Py_Initialize();
string input;
cin >> input;
/*Though the variable gets passed to a const char* definition,
the pointer is constant over the character, because the pointer ALWAYS points
to the same function*/
char const *PyCode = input.data();
exec_pycode(PyCode);
Py_Finalize();
return EXIT_SUCCESS;
}
//The execution of python code as a simple string in C and interpreting in python
void exec_pycode(const char* code)
{
Py_Initialize();
PyRun_SimpleString(code);
Py_Finalize();
}
我决定的下一步是获取包括print(“ hello world”)空格在内的字符串,这些字符串可以作为Python代码读取。
我试图将exec代码功能更改为
void exec_pycode(const char* code)
{
Py_Initialize();
const char *inFile = "FileName";
PyObject *dict = PyDict_New();
Py_CompileString(code, inFile, Py_file_input);
PyRun_String(code, Py_file_input, dict, dict);
Py_Finalize();
}
像这样更改函数时,此函数编译良好,但是当我输入任何字符串(简单或带有空格)时,程序将以0的返回值退出,而不会打印任何python代码。
我想知道为什么会发生这种情况,无论是在将用户输入转换为适当的C字符串以作为Python代码读取时是否遇到问题,还是不了解Py_CompileString(const char *str, const char *filename, int start)
or的声明PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)
,我都盯着本文档,作了记录,如图所示,我仍然得到相同的退出条件。
我也想知道:
NULL
在简化版本中将我的Python文件标志设置为而不是Py_CompileStrngFlags(...)
或Py_RunStringFlags(...)
那是导致NULL问题返回值的原因,那么我正在遇到。您的程序中不需要C标签。您的问题仅与C ++代码有关。首先,
string input;
cin >> input;
读取一个以空格分隔的单词,与scanf("%s", input);
C语言不同。您需要使用
getline(cin, input);
下一个问题是input.data()
不需要零终止。您必须 input.c_str()
改为使用。
最后:您必须始终检查调用的每个Python API函数的返回值。没有允许的快捷方式。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句