Python Forum

Full Version: How to write a script to execute a program need passing additional input?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I would like the python test.py to run a program after it been compiled to a.out and to read test.dat file:

import subprocess
import os

cmd='./a.out'
subprocess.call(cmd, shell=True)
cmd='test.data'
subprocess.call(cmd, shell=True)
the c++ program is in the test.cpp file:

#include <iostream>
#include <string>

using namespace std;

int main() {
    string filename("");
    cout<<"Please enter the file name:"<<endl;
    cin>>filename;
    cout<<"File name is: "<<filename<<endl;

    return 0;
}
execute python test.py, and it stuck there, and looks like the program are waiting for me to input 'test.data', the second subprocess.call seems not working.

How can I do this? Thanks.

So no one ever encountered this problem?
You can restructure your c++ code to process command line arguments, e.g.

#include <iostream>
#include <string>

using namespace std;

int main(int argc, char** argv) {
    string filename(""); // do something with argv[1]
    cout<<"Please enter the file name:"<<endl;
    cin>>filename; // argv[1]
    cout<<"File name is: "<<filename<<endl;
 
    return 0;
}
and run as usual:
os.call(["./a.out", "filename"])
Thank you very much, scidam!

While I am actually looking for a solution of changing on the Python side. The C++ code is mature and I prefer to leave it there.

Best!