0

I'm trying to start another script in python and then give an answer to input, this is the main script:

import subprocess
import sys
import platform

cmdline = ['py', 'ciao.py']
cmd = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
for line in cmd.stdout:
    if line == b'Loading...\r\n':
        print("sending data...")
        cmd.communicate(b"test\n")[0]
        print("done")
    print(line)
print(line)

And this is ciao.py:

import os
import re
import time
print("Loading...")
ciao = input("> ")
print(ciao)
os.system("mkdir okfunziona")
print("Done")
while 1:
    time.sleep(10)

The main script manages to send "test" but then hangs and does not print "done" to the console.

The problem is both on windows and on linux.

---------------------------------------------------------------EDIT-------------------------------------------------------------- Ok i have tested Ashish Nitin Patil's example but i see b'Loading...\r\n' output, and I do not see the other outputs of the secondary script, like ">" or "Done", it seems that the "cmd.stdout.readline ()" works only the first time because the script does not end.

1 Answers1

2

See this answer (and others on that question) for inspiration. For your case, you should not be using communicate, instead use stdin.write and stdout.readline.

Your main script might look like below -

while True:
    line = cmd.stdout.readline()
    print(line)
    if line.strip() == b'Loading...':
        print("sending data...")
        cmd.stdin.write(b"test\n")
        cmd.stdin.close()
        print("done")
    elif line.strip() == b'Done':
        break

The outputs -

b'Loading...\n'
sending data...
5
done
b'> test\n'
b'Done\n'
shad0w_wa1k3r
  • 12,955
  • 8
  • 67
  • 90
  • thanks but the output is only: b'Loading...\r\n' sending data... done It seems that the cmd.stdout.readline() works only the first time – Luc Fortunato Feb 24 '18 at 15:04
  • You are most likely stuck because `ciao.py` errs when `os.system('mkdir' ...)` would fail because of "file exists" error. Try putting it in an `if` statement, e.g. `if not os.path.exists('okfunziona'): os.system('mkdir okfunziona')` – shad0w_wa1k3r Feb 24 '18 at 20:47
  • Wow, I've always focused on the main script and I had not really thought about it, THANK YOU A THOUSAND – Luc Fortunato Feb 24 '18 at 21:07