簡體   English   中英

輸入到C ++可執行的python子進程

[英]input to C++ executable python subprocess

我有一個C ++可執行文件,其中包含以下代碼行

/* Do some calculations */
.
.
for (int i=0; i<someNumber; i++){
   int inputData;
   std::cin >> inputData;
   std::cout<<"The data sent from Python is :: "<<inputData<<std::endl;
   .
   .
   /* Do some more calculations with inputData */
}

這是在循環中調用的。 我想在python子進程中調用這個可執行文件

p = Popen(['./executable'], shell=True, stdout=PIPE, stderr=PIPE, stdin=PIPE)

我可以使用來自可執行文件的輸出

p.server.stdout.read()

但我無法使用python發送數據(整數)

p.stdin.write(b'35')

由於cin是在循環中調用的,因此stdin.write也應該多次調用(在循環中)。 以上是否可能..?

任何提示和建議我怎么能這樣做? 提前致謝。

這是如何從Python調用C ++可執行文件並從Python進行通信的簡約示例。

1)請注意,在寫入子Rtn輸入流(即stdin )時必須添加\\n (就像在手動運行程序時按Rtn一樣)。

2)還要注意流的刷新,以便在打印結果之前接收程序不會等待整個緩沖區填滿。

3)如果運行Python 3,請確保將流值從字符串轉換為字節(請參閱https://stackoverflow.com/a/5471351/1510289 )。

蟒蛇:

from subprocess import Popen, PIPE

p = Popen(['a.out'], shell=True, stdout=PIPE, stdin=PIPE)
for ii in range(10):
    value = str(ii) + '\n'
    #value = bytes(value, 'UTF-8')  # Needed in Python 3.
    p.stdin.write(value)
    p.stdin.flush()
    result = p.stdout.readline().strip()
    print(result)

C ++:

#include <iostream>

int main(){
    for( int ii=0; ii<10; ++ii ){
        int input;
        std::cin >> input;
        std::cout << input*2 << std::endl;
        std::cout.flush();
    }
}

運行Python的輸出:

0
2
4
6
8
10
12
14
16
18

暫無
暫無

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

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