解決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的事情!

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