代码之家  ›  专栏  ›  技术社区  ›  Vladimir Keleshev

Python subprocess module - unexpected behavior

  •  1
  • Vladimir Keleshev  · 技术社区  · 15 年前

    I need to interface a C console program (as subprocess) with Python using stdin/stdout.

    the C program is more o less it:

        tmp = 0.0;  
        printf("\ninput>>");
        scanf_s("%f",&tmp);
        printf ("\ninput was: %f",tmp);
    
        tmp = 0.0;
        printf("\ninput>>");
        scanf_s("%f",&tmp);
        printf ("\ninput was: %f",tmp);
    
        tmp = 0.0;
        printf("\ninput>>");
        scanf_s("%f",&tmp);
        printf ("\ninput was: %f",tmp);
    

    >>> p=subprocess.Popen(['C:\T.exe'],stdout=subprocess.PIPE,stdin=subprocess.PIPE)
    >>> o,i=communicate('123\n')
    

    the output of o is:

    input>>
    input was: 123.000000
    input>>
    input was: 0.000000
    input>>
    input was: 0.000000
    

    我希望子进程在输入之前等待,直到另一个O,i=CultAudio()调用。为什么它在没有任何输入的情况下进入程序的末尾?如何修复?

    1 回复  |  直到 15 年前
        1
  •  3
  •   Philipp    15 年前

    There can be at most one call to communicate() for each process, because 通讯() waits for the child process to terminate. To repeatedly read and write from/to a process's standard streams, use the stdout stdin attributes of the Popen 班级。