启动GUI进程而不生成黑色shell窗口

时间:2012-11-09 14:49:08

标签: python subprocess explorer

我想打开Windows资源管理器并选择特定文件。 这是API:explorer /select,"PATH"。因此导致以下代码(使用python 2.7):

import os

PATH = r"G:\testing\189.mp3"
cmd = r'explorer /select,"%s"' % PATH

os.system(cmd)

代码工作正常,但是当我切换到非shell模式(使用pythonw)时,在启动资源管理器之前会出现一个黑色的shell窗口。

os.system可以预料到这一点。我创建了以下函数来启动进程而不生成窗口:

import subprocess, _subprocess

def launch_without_console(cmd):
    "Function launches a process without spawning a window. Returns subprocess.Popen object."
    suinfo = subprocess.STARTUPINFO()
    suinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
    p = subprocess.Popen(cmd, -1, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=suinfo)
    return p

这适用于没有GUI的shell可执行文件。但是它不会启动explorer.exe

如何在不产生黑色窗口的情况下启动该过程?

1 个答案:

答案 0 :(得分:3)

似乎不可能。但是,可以从win32api访问它。我使用了here找到的代码:

from win32com.shell import shell

def launch_file_explorer(path, files):
    '''
    Given a absolute base path and names of its children (no path), open
    up one File Explorer window with all the child files selected
    '''
    folder_pidl = shell.SHILCreateFromPath(path,0)[0]
    desktop = shell.SHGetDesktopFolder()
    shell_folder = desktop.BindToObject(folder_pidl, None,shell.IID_IShellFolder)
    name_to_item_mapping = dict([(desktop.GetDisplayNameOf(item, 0), item) for item in shell_folder])
    to_show = []
    for file in files:
        if name_to_item_mapping.has_key(file):
            to_show.append(name_to_item_mapping[file])
        # else:
            # raise Exception('File: "%s" not found in "%s"' % (file, path))

    shell.SHOpenFolderAndSelectItems(folder_pidl, to_show, 0)
launch_file_explorer(r'G:\testing', ['189.mp3'])