6

我想打开 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

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

4

1 回答 1

3

这似乎是不可能的。但是可以从win32api. 我使用了这里找到的代码:

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'])
于 2012-11-09T19:42:11.980 回答