2012-11-09 59 views
6

我想打开Windows资源管理器并选择特定文件。 这是API:explorer /select,"PATH"。因此,导致下面的代码(使用python 2.7):启动GUI进程而不会产生黑色外壳窗口

import os 

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

os.system(cmd) 

的代码工作正常,但是当我切换到非壳模式(pythonw),之前的资源管理器是出现了片刻黑色外壳窗口推出。

这是与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

令人吃惊:我第C的WinExec与和ShellExec试图/ C++代码,它给我相同的行为。 – lucasg

回答

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']) 
+0

你可以看看这个问题吗?谢谢!!! http://stackoverflow.com/questions/19851113/pywin32-programming-error-on-win7-with-shell-shgetdesktopfolder-desktop-bindtoob – iMath