簡體   English   中英

將Python 3.3嵌入C ++程序中,但一次只能從輸入讀取一行

[英]Embedding Python 3.3 in a C++ program while only able to read one line at a time from input

作為暑期實習的一部分,我目前正在為大型程序添加嵌入式Python支持(是的,不能擴展)。 理想情況下,我可以將Python支持保留在單個.DLL中,該.DLL當前包含程序的內部腳本語言,並且是將所述語言與Python集成的最簡單的地方。

但是,由於該程序的API,我只能使用一個輸入函數。 該函數的返回值是當前輸入的單行,可以是控制台或文件。 無法將輸入接口(在.DLL內)轉換為流對象,緩沖區或FILE指針。

我當前的測試代碼(在程序外部編寫,使用std :: string,istream和getline來遵守該限制)是

// start python
Py_Initialize();

try
{
   cout << "Python " << Py_GetVersion() << endl;
   string block;
   bool in_block = false;
   while ( !cin.eof() )
   {
      string str;
      cout << (in_block ? "... " : ">>> "); // prompt string
      getline(cin,str);

      if ( in_block ) // if in an indented block
      {
         if ( str.front() != ' ' && str.front() != '\t' ) // if ending the indented block
         {
            PyRun_SimpleString(block.c_str());  // run Python code contained in block string
            block.clear();                      // clear string for next block
            in_block = false;                   // no longer in block
         }
         else // a component of an indented block
         {
            block += (str+'\n'); // append input to block string
            continue;            // do not pass block exit code, do not collect two hundred dollars
         }
      }

      // either not in an indented block, or having just come out of one
      if ( str.back() == ':' ) // if colon, start new indented block
      {
         block = (str+'\n');
         in_block = true;
         continue;
      }
      else { PyRun_SimpleString(str.c_str()); } // otherwise, run block-free code
   }
}
catch ( error_already_set e ) { PyErr_Print(); }

// close python
Py_Finalize();

// done
return 0;

我沒有遇到過這種駭客的嚴重問題,但讓我感到震驚,因為它非常卑鄙。 誰能想到一種更好的方法呢?

我已經和老板清除了boost.python庫,如果它提供了一些讓我難以理解的技巧。

編輯:我可能應該提到程序本身,雖然不是我微薄的測試平台,但必須在MS Windows上運行。

您寫的內容看上去與股票解釋器看起來很相似,但是除了最瑣碎的情況外,它不會遵循相同的縮進/縮進和延續規則。

嵌入交互式解釋程序外殼的最簡單方法是嵌入一個裸解釋程序,該解釋程序運行通過純Python(通常通過code模塊)編寫的交互式解釋code

為此,您必須將逐行閱讀器連接到嵌入式stdin文件對象,但是對於任何實際使用而言,無論如何您都希望這樣做。 (否則,例如,如果用戶在外殼上鍵入input() ,將會發生什么?)

一種替代方法是設置一個pty並對其進行庫存交互式解釋器(可能是子流程),從生產線閱讀器中輸入pty的輸入管道。

暫無
暫無

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

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