PyRun_SimpleString在def foo():时失败

1 投票
1 回答
1476 浏览
提问于 2025-04-17 16:25

我在使用PyRun_SimpleFile的时候遇到了问题(FILE*兼容性问题),特别是当文件名或路径中有Unicode(宽字符)时,所以我才有了这个问题!

于是,我决定自己打开Python脚本,然后用PyRun_SimpleString逐行执行。

这里是伪代码。

wchar_t* pWScriptName=NULL;
// pWScriptName malloced & populated here
FILE* fp = _wfopen(pWScriptName, L"r");
while (fgets(line, BUFSIZ, fp) != NULL) {
    int ret = PyRun_SimpleString(line);
    if(ret != 0) {
        ... error at lineNum ...
    }
    lineNum++;
}

上面的代码在下面的def语句处出错(<-- 如下所示)

我使用的Python版本是2.7

import os
print "hello"
def foo():  # <-- PyRun_SimpleString fails here
    print "hello again"

我想用这个方法来显示脚本中出错的行号。很多其他人似乎都能成功使用PyRun_SimpleString!

提前谢谢你们。

1 个回答

3

在这种情况下,你不应该使用 PyRun_SimpleString,因为它是希望一次性读取整个程序的内容,而你却把它分成了多行。

你应该直接使用 PyRun_SimpleFile(fileReference, scriptPath)

注意:你需要先创建全局和局部对象,这样上面的代码才能正常工作。

查看这个链接

撰写回答