1

I'm trying to activate CLI-based script using a python script

import random

print "This code is running"
x = random.choice(range(10))
print "The number random is: {}".format(x)

y = input("Please enter number...\n")

print "Your number: {:>3}".format(y)
print "My number:   {:>3}".format(x)
print "Are they the same? {}".format(x == y)

And i used this simple example

from subprocess import Popen, PIPE
from time import sleep

# run the shell as a subprocess:
p = Popen(['python', 'example_script.py'],
          stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=False)

def read_cli(p):
    sleep(0.1)
    msg = ''
    while True:
        t = p.stdout.read()
        if not t:
            break
        else:
            msg += '{}\n'.format(t)

    sleep(0.1)
    return msg


def write_cli(p, msg):
    sleep(0.1)

    p.stdin.write('13\n')

    sleep(0.1)


# get the output
m = read_cli(p)
print m

# Send answer
write_cli(p, 13)

# Get feedback
m = read_cli(p)
print m

But it's stuck in the first "read_cli", in the first "p.stdout.read()", it doesn't enter the next "if".

strangely, if i write first and then read - it's OK. but it doesn't help me because i need the text first.

How can i read the text first and provide the answer? does this solution work for several interactions? (question from client, answer, new question, new answer)

thx

Guy Barash
  • 470
  • 5
  • 17

0 Answers0