与 Python 中子进程中的另一个应用程序的交互式会话

Interactive session with another application in child process in Python

本文关键字:交互式 会话 应用程序 另一个 子进程 Python      更新时间:2023-10-16

我有一个用任何语言编写的应用程序(.exe)。C++并希望从 python 运行应用程序。我可以通过以下教程运行这个简单的应用程序 Python 代码 此处 https://docs.python.org/2/library/subprocess.html

from subprocess import Popen, PIPE
process = Popen([r"C:Users...x64DebugProject13.exe"],stdout = PIPE, 
stderr=PIPE, stdin = PIPE)
stdout = process.communicate(input = b"Bob")[0]
print(stdout)

C++代码:

#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
void foo(string s) {
for (int i = 0; i < 3; ++i)
{
cout << "Welcome " << s << " ";
Sleep(2000);
}
}
int main()
{
string s;
cin>> s;
foo(s);
return 0;
}

这对我来说很好用。但是,如果我多次读取应用程序中C++输入,如下所示:

#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
int main()
{
string s;
for (int i = 0; i < 3; ++i)
{
cin >> s;
cout << "Welcome " << s << " ";
Sleep(2000);
}
return 0;
}

在这里,我无法多次使用 process.communication(),因为孩子在返回时已经退出。基本上,我想以连续会议的形式与该计划互动。 我想要建议或任何其他方法来解决此问题?提前谢谢。

假设你正在Windows上工作,我建议看看namedpipes,在python端你可以使用PyWPipe,在c ++端,你必须编写自己的包装器来获取进程的消息。