如何使用整数输入参数从python调用exe并将.exe输出返回到python?

时间:2017-04-19 18:06:10

标签: python input integer subprocess exe

我已经检查过很多帖子和子流程文档但是没有提供解决方案来解决我的问题。至少,我找不到一个。

无论如何,这是我的问题描述: 我想从.py文件中调用.exe。 .exe需要一个整数输入参数,并返回一个整数值,我想用它在python中进一步计算。

为了简单起见,我想使用我的“问题”代码的最小化工作示例(见下文)。如果我运行此代码,然后.exe崩溃,我不知道为什么。也许我只是错过了什么,但我不知道是什么!?所以这就是我所做的:

我用来生成的c ++代码:MyExe.exe

#include <iostream>
using namespace std;
#include <stdlib.h>
#include <string>

int main(int argc, char* argv[])
{

int x = atoi(argv[1]);

return x;

}

我的python代码:

from subprocess import Popen, PIPE

path = 'Path to my MyExe.exe'

def callmyexe(value):
    p = Popen([path], stdout=PIPE, stdin=PIPE)
    p.stdin.write(bytes(value))
    return p.stdout.read

a = callmyexe(5)
b = a + 1
print(b)

我使用MSVC 2015和Python 3.6。

1 个答案:

答案 0 :(得分:3)

您必须使用cout作为输出:

#include <iostream>
using namespace std;
#include <stdlib.h>
#include <string>

int main(int argc, char* argv[])
{
   int x = atoi(argv[1]);
   cout << x;
}

输入的命令行参数:

from subprocess import check_output

path = 'Path to my MyExe.exe'

def callmyexe(value):
    return int(check_output([path, str(value)]))

a = callmyexe(5)
b = a + 1
print(b)