[英]how to call a exe from python with integer input arguments and return the .exe output to python?
I checked already a lot of posts and the subprocess documentation but non of them provided a solution to my problem. 我已经检查了很多帖子和子流程文档,但没有一个为我的问题提供了解决方案。 At least, i can't find one.
至少我找不到一个。
Anyway, here is my problem description: I would like to call a .exe from a .py file. 无论如何,这是我的问题描述:我想从.py文件中调用.exe。 The .exe needs a integer input argument and returns also an integer value, which i would like to use for further calculations in python.
.exe需要一个整数输入参数,并且还返回一个整数值,我想将其用于python中的进一步计算。
In order to keep things simple, i would like to use a minimun working example of my "problem"-code (see below). 为了使事情简单,我想使用我的“问题”代码的最小示例(请参见下文)。 If i run this code, then .exe crashes and i don't know why.
如果我运行此代码,则.exe崩溃,我也不知道为什么。 Maybe i just missed something but i don't know what!?
也许我只是错过了一些东西,但是我不知道!! So here is what i did:
所以这就是我所做的:
c++ code which i use to generate: MyExe.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;
}
My python code: 我的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)
I use MSVC 2015 and Python 3.6. 我使用MSVC 2015和Python 3.6。
You have to use cout
for output: 您必须使用
cout
进行输出:
#include <iostream>
using namespace std;
#include <stdlib.h>
#include <string>
int main(int argc, char* argv[])
{
int x = atoi(argv[1]);
cout << x;
}
And command line parameters for the input: 和命令行参数一起输入:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.