Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

Cannot use python subprocess to send input to console application written in C

I want to automatically test a program written in C using python. I have the C file below and the python code below. I compiled my C code into an executable (a.exe) and running it in the command prompt or normally works as expected. When I try to run it with subprocess, though, I receive no output. I tried using p1.communicate() and p1.read() as well, and both trying to send and receive input and output and only output, but to no avail. Is there a way using python (using subprocess or anything else) to run the C code below and interact with it (sending it both input and output until it closes itself)?

Output and input attempt

from subprocess import Popen, PIPE

p = Popen(['a.exe'], shell=True, stdout=PIPE, stdin=PIPE)
for ii in range(10):
    value = str(ii) + '
'
    value = bytes(value, 'UTF-8')  # Needed in Python 3.
    p.stdin.write(value)
    p.stdin.flush()
    result = p.stdout.readline().strip()
    print(result)
value = '-1
'
value = bytes(value, 'UTF-8')  # Needed in Python 3.
p.stdin.write(value)
p.stdin.flush()
result = p.stdout.readline().strip()
print(result)

Output only attempt

from subprocess import Popen, PIPE

p = Popen(['a.exe'], shell=True, stdout=PIPE, stdin=PIPE)
result = p.stdout.readline().strip()
print(result)

Example C file I'm trying to run for reference

#include <stdio.h>

int main() {
    int userInput;
    printf("Hello, this is a basic program
");
    do{
        printf("Enter user input:
");
        scanf("%d", &userInput);
        printf("The user input is: %d
", userInput);
        printf("Entering -1 will exit");
    }while(userInput != -1);
    printf("Left the loop succesfully
");
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...