Dan H Dan H - 1 year ago 115
Python Question

how to launch a command window from Python

I'd like to use Python 2.6 on Windows to launch several separate command windows, each running their own Python script. The purpose is: these are clients, and I'm trying to load up the server with requests from multiple quasi-independent clients.

I don't need to communicate with the client during or after the run, but I do need to send each a different commmandline arg, and I'd like each client's output to scroll in its own "console".

From the DOS command line, the "start" command does what I'd like. I can either:

start perf_test.py 2


start cmd /c perf_test.py 3


start cmd /c python perf_test.py 4

(These will work for you if you have your "file associations" setup correctly for *.py files. There are other threads on that, if you need help. Or, use full paths to the python exe and/or your script.)

My challenge is: How do I get the same effect from Python?

library, I've tried variations like this:

from subprocess import *
p = Popen(["perf_test.py", "4"], shell=True, stdin=PIPE)

But even with
, the output is commingled in the window I'm already running in. Adding
stops that, but then I have to read
or use
. Adding "cmd" to the Popen gets approximately the same:

p = Popen(["cmd", "/c", "perf_test.py", "4"], shell=True, stdin=PIPE)

None of the above achieve the effect I'm looking for, which is: "pop open a new, distinct window for this script, and watch its output scroll by in its own console" (because I really want to run N of these clients in parallel).

One other thing I turned to almost works, too.

import os

This returns immediately, and an actual dosbox pops up. Yay! Success! That is, until I try to add an argument. This fails:

os.startfile("perf_test.py 5")

with error "The system cannot find the file specified"... because it is adding "[SPACE]5" to the filename. (The purpose of the argument is that each "perf_test" needs to have an assigned ID, so that they hit the server as different instances.)

Other approaches I've considered, and really don't like for various reasons:

  • Run each "perf_test" in its own thread. (But I really want to see the output each in its own console.)

  • Make my own pseudo-consoles with Tk. (Figure I'll just hit different threading problems there.)

  • Dynamically write a .BAT file on the fly with the lines "start perf_test.py 1", "start perf_test.py 2", etc., then launch that .BAT file with

I expect the last will work... and I guess is my last resort, if I can't get a Python script to do it directly.

Thanks for any input / insights!

Rod Rod
Answer Source

You can use:

import os
os.system("start python perf_test.py 5")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download