Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subprocess.Popen in different console

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 the shell=True parameter but that didn't do the trick.

I use a 32 bit Python 2.7 on a 64 bit Windows 7.

like image 759
Ionut Hulub Avatar asked Apr 09 '13 10:04

Ionut Hulub


People also ask

What is the difference between subprocess Popen and OS system?

subprocess. Popen() replaces several other tools ( os. system() is just one of those) that were scattered throughout three other Python modules. If it helps, think of subprocess.

Is Popen asynchronous?

Create a subprocess: low-level API using subprocess. Popen. Run subprocesses asynchronously using the subprocess module.

How does subprocess Popen work?

Popen FunctionThe function should return a pointer to a stream that may be used to read from or write to the pipe while also creating a pipe between the calling application and the executed command. Immediately after starting, the Popen function returns data, and it does not wait for the subprocess to finish.

How can we avoid shell true in subprocess?

From the docs: args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names).


2 Answers

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?

like image 145
Pedro Vagner Avatar answered Sep 17 '22 18:09

Pedro Vagner


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) 
like image 44
Torxed Avatar answered Sep 18 '22 18:09

Torxed