简体   繁体   English

如何使用Python subprocess.call()将C ++程序读入参数传递给它?

[英]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: 基本上我正在制作一个Python程序,其中一部分需要运行C ++可执行文件,我用以下代码调用exe:

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? 但是如何让C ++程序读取输入呢? I tried: 我试过了:

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

But that just outputs 0x22ff1c and definitely not "hi". 但那只输出0x22ff1c并且绝对不是“hi”。 What code is needed to pipe the input into the C++ program? 将输入管道输入C ++程序需要什么代码?

They are passed as parameters to the main function. 它们作为参数传递给main函数。

main(int argc, char *argv[])

argc is the length of argv . argcargv的长度。 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. 对于更实质的输入/输出,您自然希望使用cout或cin,更好的选择是使用subprocess.Popen。 You can then write to and read from the other process as if they were file handles in python. 然后,您可以写入和读取其他进程,就好像它们是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. 这告诉python运行进程,传入'hi'后跟回车符号作为标准输入,然后可以在C ++程序中通过cin读取。 Standard output (the result of cout in C++) is then passed into the stdout list, and standard error is passed into stderr. 然后将标准输出(C ++中的cout结果)传递给stdout列表,并将标准错误传递给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") 如果你需要更多的交互式通信,你也可以访问proc.stdout和proc.stdin,就好像它们是python中的文件句柄一样(例如proc.stdin.write(“hi \\ n”))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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