subprocess.Popen在不同的控制台中

Ion*_*lub 22 python subprocess popen python-2.7

我希望这不是重复.

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

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

Ped*_*ner 26

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

from subprocess import Popen, CREATE_NEW_CONSOLE

Popen('cmd', creationflags=CREATE_NEW_CONSOLE)

input('Enter to exit from Python script...')
Run Code Online (Sandbox Code Playgroud)

有关

如何从基础python脚本生成新的shell来运行python脚本?


Tor*_*xed 7

from subprocess import *

c = 'dir' #Windows

handle = Popen(c, stdin=PIPE, stderr=PIPE, stdout=PIPE, shell=True)
print handle.stdout.read()
handle.flush()
Run Code Online (Sandbox Code Playgroud)

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

c = ['ls', '-l'] #Linux
Run Code Online (Sandbox Code Playgroud)

然后打开它没有shell.

handle = Popen(c, stdin=PIPE, stderr=PIPE, stdout=PIPE)
print handle.stdout.read()
handle.flush()
Run Code Online (Sandbox Code Playgroud)

这是您可以从Python调用子进程的最手动和最灵活的方法.如果您只想要输出,请选择:

from subproccess import check_output
print check_output('dir')
Run Code Online (Sandbox Code Playgroud)

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

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