简体   繁体   中英

How can I make a C++ program read arguments passed into it with Python subprocess.call()?

Basically I am making a Python program and part of it needs to run a C++ executable, I am calling the exe with:

subprocess.call(["C:\\Users\\User\\Documents\\Programming\\Python\\Utilities\\XMLremapper\\TranslatorSource\\FileFixer.exe", "hi"])

But how do I make the C++ program read the input? I tried:

FILE * input = popen("pythonw.exe", "r");
cout<< input.getline() << endl << endl;

But that just outputs 0x22ff1c and definitely not "hi". What code is needed to pipe the input into the C++ program?

They are passed as parameters to the main function.

main(int argc, char *argv[])

argc is the length of argv . So it would be

main(int argc, char *argv[])
{
 cout<<argv[1];
 return 0;
}

If you just want to pass in a few arguments, an easy option is to read arguments on the command line, as suggested in another answer.

For more substantial input/output, where you'd naturally want to use cout or cin, a better option is to use subprocess.Popen. You can then write to and read from the other process as if they were file handles in python. For example:

proc = subprocess.Popen(["FileFixer.exe"], 
            stdin=subprocess.PIPE, 
            stdout=subprocess.PIPE, 
            stderr=subprocess.PIPE)
stdout, stderr = proc.communicate("hi\n") 

This tells python to run the process, passing in 'hi' followed by carriage return as standard input, which can then be read by cin in the C++ program. Standard output (the result of cout in C++) is then passed into the stdout list, and standard error is passed into stderr.

If you need more interactive communication, you can also access proc.stdout and proc.stdin as if they were filehandles in python (eg proc.stdin.write("hi\\n")

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