Python: How to continuously communicate with another process?

41 Views Asked by At

As an example to clarify what I mean I wrote the following Python script which generates a number and lets you guess it:

import random

my_number = random.randint(0, 10)
while(1):
    input_ = int(input())
    if input_ == my_number:
        print("Correct!")
        break
    if input_ < my_number:
        print('>')
    else:
        print('<')

Now I want to automate this process with another python script. I tried it with subprocess.Popen() but I only found solutions which let me write and read once (like communicate()). Here is an example with communicate() which shows how I would like it to work but it obviously doesn't:

tcl_cmd = ["python", r"E:/number_quiz.py"]

process = subprocess.Popen(
    tcl_cmd,
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
)

my_guess = 5
while(1):
    output = process.communicate(str(my_guess).encode('utf-8'))[0]
    if output == "Correct":
        print(f"Number was: {my_guess}")
        break
    elif output == '<':
        my_guess -= 1
    else:
        my_guess +=1

Is there any way to do something like this with Python in Windows?

0

There are 0 best solutions below