0

I have two files: parent.py and child.py. I wish to use the parent to run the child script, but I want the displays within the child script to appear in the console window. Example files are below:

child.py:

from scipy import optimize
x0=1

def f(x):
    return x**2

res = optimize.fmin(f, x0, disp=True)

print('print printed')

parent.py:

import subprocess
subprocess.run(["python", "child.py"], capture_output=True)

My understanding was that the capture_output option should display the output as desired, but this does not appear to be the case. (This comes from the comment reply on my question Consecutively execute multiple python scripts which I am trying to ask here in a clearer way).

Both parent and child files are located within the same working directory, and I am using Spyder (not sure if that matters). I see what makes me think the child file is running In: runfile('C:/.../parent.py', wdir='C:/.../testing'), but I see neither the print() command nor the display from the optimize command displayed in my console. I also do not have access to the child variables once I have run the parent.

How do see the outputs (from print() and the optimize(.,disp=True) commands), as well as access the variables in the child script when running the parent?

amquack
  • 837
  • 10
  • 24
  • Do you want the output of the child script to be *displayed* or to be *captured* for use by the parent script? (Note that you can't do both at once; the best you can do is to capture and re-display, possibly in real time if needed.) – Daniel Pryden Mar 06 '19 at 20:42
  • If I can't do both, I have preference for displayed (so that I can see if the optimization gets hung up in one of the child scripts). However, it sounds like your option of the output being captured and re-displayed in real-time would be optimal. – amquack Mar 06 '19 at 20:47

1 Answers1

0

It looks like the answer is to use the following line of code in the parent file:

exec(open('child.py').read())

This runs the file as desired, allows access to the variables created by the child file, and displays all desired output.

To give credit where deserved, I found the syntax described here: What is an alternative to execfile in Python 3? and this explains the reason my previous attempts at using exec() were incorrect.

Perhaps others can improve the answer by including alternatives to those concerned about insecurities related to exec().

amquack
  • 837
  • 10
  • 24