如何使用整数输入参数从python调用exe文件并将.exe输出返回给python?
问题描述:
我已经检查了很多帖子和子过程文档,但没有提供解决我的问题的方法。至少,我找不到一个。如何使用整数输入参数从python调用exe文件并将.exe输出返回给python?
无论如何,这里是我的问题描述: 我想从一个.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。
答
你必须使用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)
你的程序不读书'stdin'(参见对于C'cin' ++)它正在读取命令行参数。你没有提供命令行参数,所以没有元素'argv [1]',所以它崩溃 - 尽管确切的行为是未定义的。你的C++程序不写入'stdout'(参见'cout'),它返回一个数字。你似乎混淆了命令行参数,返回语句和标准流 - 它们没有关系。 – cdarke
[在Python中调用外部命令]可能的重复(http://stackoverflow.com/questions/89228/calling-an-external-command-in-python) –
顺便说一下,'p.stdout.read'只是返回一个方法对象,你可能的意思是'p.stdout.read()'(但这不起作用,因为你的程序没有写入'stdout')。 – cdarke