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

2024-04-25 00:47:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个应用程序(.exe),用任何语言编写,如C++,希望从Python运行应用程序。我可以通过使用下面的示例Python代码来运行这个简单的应用程序,方法是遵循这里的教程https://docs.python.org/2/library/subprocess.html

from subprocess import Popen, PIPE

process = Popen([r"C:\Users\...\x64\Debug\Project13.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;
}

在这里我不能使用过程.沟通()多次,因为孩子在离开时已经离开了回报。基本上我想作为一个连续的会议与该方案进行互动。 我想要一些建议或其他方法来用python解决这个问题?提前谢谢。你知道吗


Tags: 方法代码应用程序stringincludewindowsstdoutprocess
1条回答
网友
1楼 · 发布于 2024-04-25 00:47:29

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

相关问题 更多 >