解决PyRun_SimpleFile/PyRun_SimpleString报错

问题:
Debug调试运行至PyRun_SimpleFile时报错

0x00007FF9B9B22208 (ucrtbase.dll) (test.exe 中)处有未经处理的异常: 将一个无效参数传递给了将无效参数视为严重错误的函数。

Rlease下运行正常不会报错

解决:
不要使用fopen,改用_Py_fopen

FILE *fp = _Py_fopen( "test.py", "r+" );

问题:
执行"import cv2"时报错

C:\ProgramData\Anaconda3\lib\site-packages\numpy\\_\_init\_\_.py:140: UserWarning: mkl-service package failed to import, therefore Intel\(R\) MKL initialization ensuring its correct out-of-the box operation under condition when Gnu OpenMP had already been loaded by Python process is not assured. Please install mkl-service package, see http://github.com/IntelPython/mkl-service
  from . import \_distributor\_init
ImportError: numpy.core.multiarray failed to import
Traceback (most recent call last):
  File "image3D.py", line 2, in \<module\>
    import cv2 #导入opencv库
  File "C:\ProgramData\Anaconda3\lib\site-packages\cv2\\_\_init\_\_.py", line 3, in \<module\>
    from .cv2 import *
ImportError: numpy.core.multiarray failed to import

numpy版本与opencv版本不匹配,此处的opencv-python 4.2.0.32,而numpy 1.18.1,应该更新为numpy 1.18.2
先卸载旧的的numpy

pip uninstall numpy

然后

pip install numpy

问题:缩进导致的错误IndentationError: unindent does not match any outer indentation level

原因:
python代码前后缩进量不一致,或者缩进符号不一致,如一处用tab另一处用回车。
C++的字符串分行的不同写法,以下写法会导致错误

PyRun_SimpleString(
	"if 1<2:\n \
	\ta=2\n \   //前面有多余的空格
	else:\n \   //前面有多余的空格
	\ta=3");    //前面有多余的空格

这是因为每行前面的空白部分也算进字符串了,我们将每行顶格写:

PyRun_SimpleString(
"if 1<2:\n \  
\ta=2\n \   //'\n'与反斜杠之间隔了一个空格,但这个空格却跑到下一行"else"之前了!
else:\n \
\ta=3");

依旧报错,’\n’ 和 \ 之间不要写空格,再次修改:

PyRun_SimpleString(
"if 1<2:\n\
\ta=2\n\
else:\n\
\ta=3");

这次就正常了,但这样写观感不好,再改:

PyRun_SimpleString(
	"if 1<2:    \n" \
	"    a=2    \n" \
	"else:      \n" \
	"    a=3");

每行用一组双引号括起来,行末写反斜杠,这样看起来就舒服多了


问题:分支语句PyRun_SimpleString("if 1<2:");执行后报错SyntaxError: unexpected EOF while parsing

分支语句不能逐行调用PyRun_SimpleString,一个完整的分支语句用一次PyRun_SimpleString,参考上一个问题的做法


问题:多线程下程序跑飞
原因:每个线程对应一个Python解析器实例,只有在本线程内调用过Py_Initialize才能创建一个解析器实例,该解析器只能在本线程内运行python代码(调用PyRun_SimpleString或PyRun_SimpleFile),跨线程调用会导致程序跑飞
不要做在主线程Py_Initialize,在子线程PyRun_SimpleString的事情!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章