簡體   English   中英

如何阻止 python 依賴項退出?

[英]How can I stop a python dependency from exiting?

我在我的代碼中調用了第 3 方 python 庫,它響應異常情況只是簡單地exit而不是raise異常。 我認為exit本身不是來自 python 本身,而是來自鏈接的 C 文件。 在 linux 上使用strace肯定表明它正在調用退出。

不幸的是,這會導致我的整個程序退出。 我想要的是能夠捕獲這個“退出”事件並引發異常,然后讓我的處理代碼對參數進行一些更改並再次調用。 我正在尋找捕獲退出事件的方法,到目前為止,我已經看到了atexit ,它實際上似乎不允許您繼續執行,而且我可以將調用隔離在子進程中以將自己與出口隔離事件。 這對我來說似乎太不優雅了,所以我想知道是否有其他人可以權衡這里可以做些什么。

在這一點上我還沒有嘗試任何具體的東西,我只是在尋找解決這個問題的可能方法。

正如上面評論中所指出的,如果不創建子流程,實際上是沒有辦法做到這一點的。 最后,我最終(ab)使用 python multiprocessing庫來解決這個問題。 解決方案如下所示:

import multiprocessing as mp
import unsafe_module  # my external dependency that hard exits unexpectedly


def access_unsafe_module_safely(unsafe_args, pipe):
    unsafe_obj = unsafe_module.UnsafeClass()
    
    # the next line causes the process to exit when certain args are passed
    results = unsafe_obj.do_unsafe_thing(unsafe_args)
    
    # report the results using multiprocessing.Pipe
    pipe.send(results)


# unsafe_args are passed in from the user
def main(unsafe_args):
    (receive_end, send_end) = mp.Pipe(False)  # False gives non-duplex mode

    # the target callable is invoked with args, which must be iterable
    process = mp.Process(target=access_unsafe_module_safely, args=(unsafe_args, send_end))
    process.start()
    process.join()  # waits until the subprocess is complete

    # if you know your module's exit codes, you can be smarter here
    if process.exitcode != 0:  # generally signals error
        raise RuntimeError("something bad happened in unsafe_module")
    
    # gets the returned results from the subprocess
    results = receive_end.recv()

    # (Python 3.7+) cleans up the subprocess resources
    process.close()
    
    # continue on with results from here...

不幸的是,去圖書館維護者那里沒有什么意義。 它是用於科學 C/C++ 應用程序的 Python 綁定。 exit非常適合他們的設計案例。

暫無
暫無

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

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