User Tools

Site Tools


how-to-spawn-shells-in-windows

Spawning Shells in Windows

In Windows, to spawn new shells which don't automatically close and run the current python program, start from the following template:

import os, sys
import argparse
import subprocess
# from pipes import quote # not used here, but necessary if doing it the os.system way
from time import sleep
import threading


if __name__ == '__main__':

  THREAD_POOL = []

  ap = argparse.ArgumentParser()
  ap.add_argument("--num", default=1)
  ap.add_argument('--spawned', action='store_true')
  args = ap.parse_args()

  def spawn_1():
    p = subprocess.Popen(["start", "/wait", "cmd", "/k", "python", os.path.realpath(__file__), "--spawned"] + sys.argv[1:], shell=True)
    p.wait()

  if args.spawned:
    print("Hello, world.")
    sleep(10)
  else:
    for i in range(0, int(args.num)):
      t = threading.Thread(target=spawn_1)
      THREAD_POOL.append(t)
      t.start()

    for t in THREAD_POOL:
      t.join()

I'm spawning multiple instances by wrapping the subprocess in a thread which is then joined with main execution later. The program will terminate when all open command windows are closed.

how-to-spawn-shells-in-windows.txt · Last modified: 2018/01/23 16:52 by 198.154.31.4

Bitnami