簡體   English   中英

Python 2-為什么“ with”在嵌入式C代碼中表現不同?

[英]python 2 - why does 'with' behave differently in embedded c code?

我正在嘗試在ac / c ++ DLL中使用python 2.7.5。 此DLL由另一個使調試成為挑戰的應用程序使用。 經過數小時的努力,我已經將問題隔離到“ with”語句中讀取的文件引發異常的地方。 我不明白...如果正確實施,“ with”應該吸收異常,對嗎? 無論如何,從命令行調用相同的python代碼完全沒有問題。

我的C / CPP DLL稱為...

def parsetest(filename):
     bytesin = getMD3Bytes(filename)
     return bytesin

def getMD3Bytes(filename):
     filename = 'lower.md3'
     bytes = ''
     valuetoreturn = 1
     try:
          with open(filename,'rb') as fileptr:
               if fileptr != None:
                    bytes = fileptr.read()
                    valuetoreturn = 333
     except:
          valuetoreturn = 991
     return valuetoreturn

如果DLL通過以下方式運行此代碼:

pValue = PyObject_CallObject(pFunc, arguments);

並通過...獲得結果

iResult = PyInt_AsLong(pValue);

iResult的值為991而不是333,只有在'with'內未發生異常時才會發生。 我知道,因為我讓調用DLL的應用程序彈出了一個帶有iResult的消息框。

對我來說更有趣,這有效...

C:\Program Files (x86)\DeleD CE\Plugins>python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import parseMD3
>>> testval = parseMD3.parsetest('junk')
>>> print testval
333
>>> exit()

那么,為什么CLI python返回一個不同的結果,即從PyObject_CallObject調用相同的代碼? 為什么“ with”在這里表現不同?

with不處理異常。 它僅確保在發生異常時關閉文件。 如果open()表達式本身發生異常,則甚至不會輸入with塊。 fileptr也永遠不會綁定到None

您正在捕獲所有異常,包括鍵盤中斷和內存錯誤,因此我們無法在此處開始說明為什么在C ++控制下運行時代碼失敗。

堅持使用一組有限的異常,例如IOError ,並正確記錄該異常:

import logging

logger = logging.getLogger('__name__')

def getMD3Bytes(filename):
    filename = 'lower.md3'
    bytes = ''
    valuetoreturn = 1
    try:
        with open(filename,'rb') as fileptr:
            bytes = fileptr.read()
            valuetoreturn = 333
    except IOError:
        logger.exception('Failed to open file properly')
        valuetoreturn = 991
    return valuetoreturn

記錄器的默認配置將輸出到stderr ,但是您可以將其配置為登錄到文件:

logging.basicConfig(filename='/tmp/debug.log', level=logging.DEBUG)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM