【问题标题】:PyRun_SimpleString fails for def foo():PyRun_SimpleString 对于 def foo() 失败:
【发布时间】:2013-02-19 21:48:53
【问题描述】:

对于名称/路径中包含 unicode (widechar) 的文件,我无法让 PyRun_SimpleFile 工作(FILE* 兼容性问题),因此出现了这个问题!

所以,我决定自己打开 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++;
}

Above 在下面的 def 语句中给出错误(

Python 版本是 2.7

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

我想用它来显示如果/它失败的脚本的行号。许多其他人似乎使用 PyRun_SimpleString 取得了成功!

提前致谢。

【问题讨论】:

  • PyRun_SimpleString 需要一个完整的源代码字符串,而不是其中的一行。

标签: c++ python python-embedding


【解决方案1】:

在这种情况下,您不会使用 PyRun_SimpleString,因为它希望在一行中读取整个程序,您将其分成多行。

你应该只使用PyRun_SimpleFile(fileReference, scriptPath)

注意:您需要创建 globals 和 locals 对象才能使上述工作。

See this

【讨论】:

  • 问题是 PWScriptName 是 wchar_t*。我已经更新了这个问题。但如前所述,我无法让 PyRun_SimpleFile 在其路径/名称中用于文件剃须宽字符。
  • 这种情况你不传wchar_t*,需要给它(fp, scriptPath)
  • 我知道。所有将 FILE* 作为参数的 PyRun API 都会崩溃,因为 VC2010 和 Python 的 FILE 结构不匹配。这是一个有据可查的问题,尤其是对于 Windows。
  • 我将此标记为答案。制作整个脚本的缓冲区并将其传递给 PyRun_SimpleString。在这种情况下,无法进行错误检测。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-25
  • 2011-03-26
  • 2022-09-04
  • 1970-01-01
  • 1970-01-01
  • 2014-05-03
  • 2020-03-28
相关资源
最近更新 更多