subprocess.Popen in different console
Solution 1
from subprocess import *
c = 'dir' #Windows
handle = Popen(c, stdin=PIPE, stderr=PIPE, stdout=PIPE, shell=True)
print handle.stdout.read()
handle.flush()
If you don't use shell=True
you'll have to supply Popen()
with a list instead of a command string, example:
c = ['ls', '-l'] #Linux
and then open it without shell.
handle = Popen(c, stdin=PIPE, stderr=PIPE, stdout=PIPE)
print handle.stdout.read()
handle.flush()
This is the most manual and flexible way you can call a subprocess from Python. If you just want the output, go for:
from subproccess import check_output
print check_output('dir')
To open a new console GUI window and execute X:
import os
os.system("start cmd /K dir") #/K remains the window, /C executes and dies (popup)
Solution 2
To open in a different console, do (tested on Win7 / Python 3):
from subprocess import Popen, CREATE_NEW_CONSOLE
Popen('cmd', creationflags=CREATE_NEW_CONSOLE)
input('Enter to exit from Python script...')
Related
How can I spawn new shells to run python scripts from a base python script?
Solution 3
On Linux shell=True will do the trick:
command = 'python someFile.py'
subprocess.Popen('xterm -hold -e "%s"' % command)
Doesn't work with gnome-terminal as described here:
https://bbs.archlinux.org/viewtopic.php?id=180103
Ionut Hulub
Cloud Engineer at Cloudbase Solutions Student of computer science at FII. Twitter: @ionuthulub Linkedin: Ionut Hulub Tip.me: ionuthulub.tip.me
Updated on June 01, 2020Comments
-
Ionut Hulub almost 4 years
I hope this is not a duplicate.
I'm trying to use
subprocess.Popen()
to open a script in a separate console. I've tried setting theshell=True
parameter but that didn't do the trick.I use a 32 bit Python 2.7 on a 64 bit Windows 7.
-
A.Joly over 6 yearsthat's what I was looking for, thanks :) ... now I have to set a tempo before launching my other task ...
-
Andrey Moiseev over 4 yearsThis should be the accepted answer. The solid way of opening a new console window in Windows is explicitly supplying the WINAPI process creation flags. Other solutions rely on Python implementation side-effects.