3

I have to files, main.py and child.py.

I am trying to send a string to the stdin of main.py.

This is my incomplete code:

main.py

from subprocess import *
import time

def main():
    program = Popen(['python.exe'. 'child.py', 'start'])
    while True: #waiting for'1' to be sent to the stdin
        if sys.stdin == '1':
            print('text)

if __name__ == '__main__':
    main()

child.py

import sys

if sys.argv[1] == 'start':
    inp = input('Do you want to send the argument?\n').lower()
    if inp == 'no':
        sys.exit()
    elif inp == 'yes':
        #Somehow send '1' to the stdin of 1.py while it is running

I have no idea how to do this.

I am running windows 10 with python 3.5.1

-Thanks

EDIT: When I am sending the argument back to main.py, I can not re-open the program. os.system re-opens the program which is not useful in my case.

These programs are a small demo of what I am trying to do. In my actual program, I am not able to do that as the two programs are "communicating" with each other an need to be open at all times.

What I need answered is a way to send an argument to main.py perhaps using stdin but when I am sending my argument, It can not re-open the program. Some examples like os.system re-open the program which is not what I am trying to do. I need main.py open at all times.

I have my new current code which is not working. A window pops up and then closes.

main.py

from subprocess import Popen, PIPE, STDOUT
x = Popen(['python.exe', '2.py', 'start'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
while x.poll() is None:
    if b'Do you want to send the argument?' in x.stdout.read():
        x.stdin.write(b'yes\n')

child.py

import sys
import time
time.sleep(1)
if 1 = 1:
    inp = input('Do you want to send the argument?\n').lower()
    if inp == 'no':
        sys.exit()
    elif inp == 'yes':
        sys.stdout.write('1')
        sys.stdout.flush()

That is my code.

13
  • Why not just do import child? Commented Jun 1, 2016 at 5:58
  • Generic question: why do you want to do this? What is the context? Commented Jun 1, 2016 at 6:01
  • @VikasMadhusudana No, it's not: Popen already does that here. It's about passing stdout to the stdin of another program (in this case the parent), which in *nix parliance is shell related, not really Python. Commented Jun 1, 2016 at 6:03
  • The way I'm using this program, I cant just import child. @Torxed Commented Jun 1, 2016 at 6:03
  • The way main.py and child.py looks, yes you can because child would inherit sys.argv from the parent and there's also other ways to do regular python imports with custom arguments and global Variables. Commented Jun 1, 2016 at 6:05

1 Answer 1

9

What you need is something along the lines of (in main.py):

from subprocess import Popen, PIPE, STDOUT
x = Popen(['some_child.exe', 'parameter'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)

while x.poll() is None:
    child_output = x.stdout.readline()
    print(child_output)
    if b'Do you want to send the argument?' in child_output:
        x.stdin.write(b'yes\n')
        x.stdin.flush()
x.stdout.close()
x.stdin.close()

You're assuming child.exe (in your mockup demo, python.exe) is communicating with main.py via sys.stdin/stdout, however these I/O's are used to communicate with the shell that spawned the process.

Much like the childs stdout/stdin will be communicating with the shell that spawned that process, in this case Popen().

Each spawned child process of subprocess.Popen(...) will be isolated with it's own stdout/stdin/stderr, otherwise every subprocess would make a huge mess of your main process stdout/stdin. This means you'll have to check for output on that particular subprocess and write to it accordingly as done in the above example.

One way to look at it is this: enter image description here

You're starting main.py, and you communicate with it via sys.stdout and sys.stdin. Each input() in main.py will output something to sys.stdout so you can read it.

Exactly the same logic applies to child.exe where every input() will output something to it's sys.stdout (- But remember - sys is not a shared variable across processes).

import sys

if sys.argv[1] == 'start':
    inp = input('Do you want to send the argument?\n').lower()
    if inp == 'no':
        sys.exit()
    elif inp == 'yes':
        #Somehow send '1' to the stdin of 1.py while it is running
        sys.stdout.write('1')
        sys.stdout.flush()

But a simple print(1) would do the same because it will essentially output the 1 to sys.stdout for you.

Edit 2018: Don't forget to close your inputs and outputs, as they might leave open file descriptors on your file system, hogging resources and causing problems later in life.

Other conveyers of information

Assuming you have control of the code to child.exe and you can modify the communication pipe in any way, some other options are:

More cautionary tails!

  • .readline() will assume there's a \n somewhere in your data, most likely at the end. I switched to .readline() for two reasons, .read() will hang and wait for EOF unless you specify exactly how many bytes to read, if I'm not out on a bicycle. To be able to read all kinds of output you need to incorporate select.select() into your code - or a buffer of some sort where you call x.stdout.read(1) to read one byte at a time. Because if you try to read .read(1024) and there's not 1024 bytes in the buffer, your read will hang until there are 1024 characters.

  • I left a bug in your child.py code on purpose (mine works) - It's trivial and basic Python - in hopes that it's a learning experience on how to debug errors (you mentioned you're not good at it, this is a way to learn).

Sign up to request clarification or add additional context in comments.

40 Comments

Okay, I kind of get what you mean. Could you give an example with using the stdout? @Torxed
@nic there's an example at the top of my answer? It's not perfect because I'm coding on me phone. I can perfect the code in a sec.
okay, can you give the example with both the two files code? The reason why I say anoth example is because child.py has no variable "x" as it dose not have main.py open as a variable "x". Thanks
@SilentMonk Depending on what you mean with buffering in this case. Yes, if you do not empty the buffer of x.stdout, buffering will hang the process - There for it's extremely important to empty the IO buffer.
@SilentMonk and yes, if the full output is not complete but in fact divided mid way my if statement won't catch the expected output. Kept it simple tho because OP is already confused about the IO. Should mention it tho.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.