subprocess.Popen在不同的控制台中

时间:2013-04-09 10:43:11

标签: python python-2.7 subprocess popen

我希望这不是重复。

我正在尝试使用subprocess.Popen()在单独的控制台中打开脚本。我已经尝试设置shell=True参数,但这并不能解决问题。

我在64位Windows 7上使用32位Python 2.7。

4 个答案:

答案 0 :(得分:20)

要在其他控制台中打开,请执行(在Win7 / Python 3上测试):

from subprocess import Popen, CREATE_NEW_CONSOLE

Popen('cmd', creationflags=CREATE_NEW_CONSOLE)

input('Enter to exit from Python script...')

相关

How can I spawn new shells to run python scripts from a base python script?

答案 1 :(得分:6)

from subprocess import *

c = 'dir' #Windows

handle = Popen(c, stdin=PIPE, stderr=PIPE, stdout=PIPE, shell=True)
print handle.stdout.read()
handle.flush()

如果您不使用shell=True,则必须为Popen()提供列表而不是命令字符串,例如:

c = ['ls', '-l'] #Linux

然后在没有shell的情况下打开它。

handle = Popen(c, stdin=PIPE, stderr=PIPE, stdout=PIPE)
print handle.stdout.read()
handle.flush()

这是您可以从Python调用子进程的最手动和最灵活的方式。 如果您只想要输出,请转到:

from subproccess import check_output
print check_output('dir')

要打开新的控制台GUI窗口并执行X:

import os
os.system("start cmd /K dir") #/K remains the window, /C executes and dies (popup)

答案 2 :(得分:4)

我在Win7 / python 2.7上尝试过creationflags = CREATE_NEW_CONSOLE,这也很有效。

答案 3 :(得分:-1)

在Linux shell = True上可以解决问题:

command = 'python someFile.py' subprocess.Popen('xterm -hold -e "%s"' % command)

不适用于此处所述的gnome-terminal:

https://bbs.archlinux.org/viewtopic.php?id=180103

相关问题