File: pyedit-products/unzipped/docetc/examples/RunCode-examples/

test running other programs that spawn other programs
the only catches here: sys.executable may not be a Python
when PyEdit is frozen, and some spawners may need to unset
the subprocprocy's PYTHONHOME+PYTHONPATH for the Mac app;
the proxy also expects stream text to be utf8 Unicode; 
to sidestep all such contraints, set your's
Python exe path to a locally-installed Python, or use the
source-code version of PyEdit instead of a frozen app.exe;

from __future__ import print_function
import os, subprocess, sys

proc = os.path.abspath('')         # abs for system.popen
os.environ['PYTHONIOENCODING'] = 'utf8'

print('cwd:', os.getcwd())
print('exe:', sys.executable)
print('run:', proc)

os.system(proc)                              # need abspath on mac

print(os.popen(proc).read())                 # need abspath on mac

if sys.executable.lower().endswith(('python', 'python.exe', 'python3')):
    # being run by a standalone python 
    cmdseq = [sys.executable, '-u', proc]    # -u for py unbuffered (more or less)
    # being run by frozen subprocproxy
    cmdseq = [proc]
print('cmd:', cmdseq)

# 1.5: shell should be True on Windows so that it uses filename associations,
# but False on Linux so that it doesn't just start a "python" interactive shell 
doshell = sys.platform.startswith('win') 

# spawn mergeall
subproc = subprocess.Popen(
              cmdseq,                     # a string cmd may fail on Unix
              shell=doshell,              # see note above, platform specific
              universal_newlines=False,   # binary mode, manual decode/eoln
              stdout=subprocess.PIPE,     # capture sub's stdout here
              stderr=subprocess.STDOUT)   # route sub's stderr to its stdout

for line in subproc.stdout:        # read stdout+stderr lines: may block this thread
    print('\t=>' + repr(line), line.decode('utf8').rstrip()) 

[Home page] Books Code Blog Python Author Training Search ©M.Lutz