简体   繁体   English

使用子进程写入标准输入

[英]Writing into stdin with subprocess

I have the following C Program我有以下 C 程序

#include <stdio.h>


int main()
{

    char a[200];
    a[199] = 0;


    printf("Enter some input ->\n");
    scanf("%s"  ,a);

    printf ("\nInput was %s\n", a);

    return 0;
}   

and I'm trying to write some input into it the following way:我正在尝试通过以下方式向其中写入一些输入:

from subprocess import *
a = Popen(["my_prog.elf", stdin=PIPE) 
a.stdin.write("MyInput")

yet this doesn't appear to work.... any ideas how to fix this?但这似乎不起作用......任何想法如何解决这个问题?

** edit ** ** 编辑 **

does anyone have any clue why a.stdin.flush() wont work?有没有人知道为什么a.stdin.flush()不起作用?

scanf reads one whole line, until it reads the new line character \\n , so you have to send this, too: scanf读取一整行,直到它读取新行字符\\n ,所以你也必须发送这个:

from subprocess import Popen, PIPE
a = Popen(["my_prog.elf"], stdin=PIPE) 
a.stdin.write("MyInput\n")

flush is only needed, if your output stream ( stdin ) is buffered (which pipes are not, by default).如果您的输出流 ( stdin ) 被缓冲(默认情况下哪些管道不是),则只需要flush Even then, you need \\n to terminate the line.即使这样,您也需要\\n来终止该行。

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

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