From within a python script ("main.py"), I am using the subprocess module to run another script ("sub_script.py").
Here's the code in the "main.py" script that 'runs' "sub_script.py":
subprocess.Popen([sys.executable, "sub_script.py"])
this works fine as long as "sub_script.py" does not have any "print" statements in it.
I now want to channel all the output of "sub_script.py" to an external file ("log.txt").
How do I do it?
import sub_script? Why all this extra subprocess business?importand launching a subprocess do fundamentally different things. For starters, the script won't run with import at all if it usesif __name__ = "__main__":block, you'd have trouble forwarding the output (which is required here), and your main script would need to wait for the subscript to finish. Also you can't really import a script in the general case (because you don't have any guarantee that it is a .py file in the python path).import sub_scriptis not the entire line of code required, more would be needed, clearly. "Forwarding the output" from the original script and the original script which imports and executessub_script.pydoes not change. I'm not sure what "import a script in the general case" means since importing a script requires some design work, i.e., settingPYTHONPATH. The question remains. Why not simply import and executesub_script? Why try to use subprocess?