0

Problem

I have a third-party program (written in C++) that I want to use in my Python code. The program takes three arguments as follows:

$ program.exe [arg1] [input_file] [output_file]

The way I'm using it for now is by writing the input file, use subprocess.run() and read the output file like this:

import subprocess

def execute_program(arg1, input):
    with open('file.in', 'w') as f:
        f.write(input)

    cmd = ['program.exe', arg1, 'file.in', 'file.out']
    completed_process = subprocess.run(cmd, stderr=subprocess.PIPE)

    with open('file.out', 'r') as f:
        result = f.read()

    return result

Now there are several problems with this, like taking care that the files are erased after execution, having to work with timestamps (or other solutions) when running the code in parallel and overall it just feels plain ugly.


Question

Is there a "cleaner" way of doing this? Can I pass the input and capture the output directly through Python or is there no way of avoiding writing (temporary) files?

Community
  • 1
  • 1
chickenNinja123
  • 311
  • 2
  • 11
  • as you can see, it's a exe file that you are calling. The program doesn't provide any api? – JNo Jun 04 '20 at 18:02
  • An API to what? It’s a compiled C++ code and I just put the .exe extension there for emphasis. – chickenNinja123 Jul 14 '20 at 19:29
  • It's an exe program that takes some inputs and writes some outputs. how you can get the processed data of the c++ code if you don't have access to the source code? and if you have, expose that particular function that holds the results to Python using libraries like pybind11 – JNo Jul 15 '20 at 10:43

0 Answers0