简体   繁体   中英

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. The .exe needs a integer input argument and returns also an integer value, which i would like to use for further calculations in 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. 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

#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:

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.

You have to use cout for output:

#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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM