Python subprocess.Popen 在不同的控制台
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15899798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
subprocess.Popen in different console
提问by Ionut Hulub
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=Trueparameter but that didn't do the trick.
我正在尝试使用subprocess.Popen()在单独的控制台中打开脚本。我试过设置shell=True参数,但这并没有奏效。
I use a 32 bit Python 2.7 on a 64 bit Windows 7.
我在 64 位 Windows 7 上使用 32 位 Python 2.7。
采纳答案by Torxed
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=Trueyou'll have to supply Popen()with a list instead of a command string, example:
如果不使用shell=True,则必须提供Popen()列表而不是命令字符串,例如:
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:
这是您可以从 Python 调用子流程的最手动和最灵活的方式。如果你只想要输出,去:
from subproccess import check_output
print check_output('dir')
To open a new console GUI window and execute X:
要打开一个新的控制台 GUI 窗口并执行 X:
import os
os.system("start cmd /K dir") #/K remains the window, /C executes and dies (popup)
回答by Pedro Vagner
To open in a different console, do (tested on Win7 / Python 3):
要在不同的控制台中打开,请执行(在 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?
回答by David Wallace
I tried creationflags=CREATE_NEW_CONSOLE on Win7/python 2.7 and that also worked.
我在 Win7/python 2.7 上尝试了 creationflags=CREATE_NEW_CONSOLE 并且也有效。
回答by blented
On Linux shell=True will do the trick:
在 Linux shell=True 上可以解决问题:
command = 'python someFile.py'
subprocess.Popen('xterm -hold -e "%s"' % command)
command = 'python someFile.py'
subprocess.Popen('xterm -hold -e "%s"' % command)
Doesn't work with gnome-terminal as described here:
不适用于此处所述的 gnome-terminal:

