我有一個cplusplus共享庫,具有c接口,寫入標準輸出日誌條目。我在使用庫的python應用程序中使用它。 python應用程序使用logging
庫來寫入日誌條目。捕獲與ctypes C++共享庫日誌條目
我需要做的是捕獲共享庫的stdout條目,以便用logging
模塊寫入日誌條目。換句話說,我想將c庫的標準輸出項重定向到logging
模塊,因此我可以使用logging
使用其處理程序寫入文件和控制檯。
我發現可以捕獲標準輸出(see this SO question),但只有在c模塊調用結束時纔可以訪問它,因此對於日誌記錄來說它是無用的。我想要一種無阻塞的方式來訪問stdout條目。
最小的例子如下。
module.cpp(與g++ -fPIC -shared module.cpp -o module.so
編譯)
#include <unistd.h>
#include <iostream>
using namespace std;
extern "C" int callme()
{
cout<<"Hello world\n";
sleep(2);
cout<<"Some words\n";
sleep(2);
cout<<"Goodby world\n";
return 0;
}
的Python應用程序調用它:
import ctypes as ct
import logging
format='%(asctime)s - %(levelname)s - %(message)s', level=logging.DEBUG
logging.basicConfig(format=format)
logging.debug('This logging modules works like a charm!')
mymodule = ct.CDLL('./module.so')
mymodule.callme()
logging.info('I want to capture the shared library log entries')
logging.warning('Can I?')
這將產生:
2016-02-04 16:16:35,976 - DEBUG - This logging modules works like a charm!
Hello world
Some words
Goodby world
2016-02-04 16:16:39,979 - INFO - I want to capture the shared library log entries
2016-02-04 16:16:39,979 - WARNING - Can I?
我可以訪問C++庫,因此需要在庫中進行修改的解決方案也是受歡迎的。
「,但我可以訪問它,只有當c模塊調用結束「 - 你確定嗎?你不能在另一個線程中運行模塊調用,或者在另一個線程中執行管道檢查嗎? – Claudiu
@Claudiu感謝您的關注。這句話我的意思是說,另一個問題的答案不會「按原樣」工作。我沒有嘗試你提出的基於線程的解決方案,我會嘗試。但與此同時,如果你可以用這個想法寫一個答案,它將非常感謝:) – eguaio