4

I have an interesting set of requirements that I am trying to conduct using the Python subprocess module. I would like to create a child process from a parent process, pass data to that child process from the parent, and display that data on a separate console of the child. Essentially, the child process must be able to output to its very console screen.

The biggest culprit seems to be stdin=subprocess.PIPE. When I include such a parameter within subprocess, I can successfully pass data to the child process using the communicate method, but I cannot print or view output in its very own console window. When I remove the stdin=subprocess.PIPE, I obviously cannot pass data from parent to child, but any generic print/output statement within the child can be successfully executed in its own console. It's one or the other. Is there away that I can have my cake and eat it too using subprocess?

An example of a successful use case of passing data from 'parent.py' to 'child.py' can be found here: Python3 subprocess communicate example

The code below does not work, but it is does illustate what I want to do by sending a string to the child and attempting to output it to the new console screen. The console is created, but I cannot see any print dialogue. If I remove stdin=subprocess.PIPE and completely avoid passing data to child, output to console works fine. Regardless, the time call works, so child.py is certainly executing data.

Parent.py

    import subprocess

    msg = "this is a message from parent"
    p = subprocess.Popen([python.exe, "Child.py"], stdin=subprocess.PIPE,
                          creationflags=subprocess.CREATE_NEW_CONSOLE)
    p.communicate(msg)

Child.py

    import time

    msg = input()
    print msg
    time.sleep(3.0)

Thank you for your help!

Edit 1

p = subprocess.Popen([sys.executable, "Child.py"], stdin=subprocess.PIPE,
                      stdout=subprocess.PIPE, stderr=subprocess.PIPE)

Does not work for me. My intent is NOT to redirect the stdout. I want to maintain the stdout of the new child process to console but use stdin=pipe to send data to that process. When stdin is set for the pipe, I can send data to the child, but I cannot output any data nor run any functions (i.e. print) to show output in the child's window. That's what I'm trying to do.

Community
  • 1
  • 1
  • Are you actually holding the ``p`` variable? If it gets GC'd it can cause weird things to happen. – aruisdante Apr 04 '14 at 22:06
  • 1
    Also note that ``CREATE_NEW_CONSOLE`` is a windows-only feature, so your code won't be portable, if that's a concern for you. – aruisdante Apr 04 '14 at 22:21

0 Answers0