簡體   English   中英

使用子進程寫入標准輸入

[英]Writing into stdin with subprocess

我有以下 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;
}   

我正在嘗試通過以下方式向其中寫入一些輸入:

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

但這似乎不起作用......任何想法如何解決這個問題?

** 編輯 **

有沒有人知道為什么a.stdin.flush()不起作用?

scanf讀取一整行,直到它讀取新行字符\\n ,所以你也必須發送這個:

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

如果您的輸出流 ( stdin ) 被緩沖(默認情況下哪些管道不是),則只需要flush 即使這樣,您也需要\\n來終止該行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM