iTa*_*ayb 6 python explorer subprocess
我想打开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)
Run Code Online (Sandbox Code Playgroud)
代码工作正常,但当我切换到非shell模式(with 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
Run Code Online (Sandbox Code Playgroud)
这适用于没有GUI的shell可执行文件.但它不会发布explorer.exe.
如何在不产生黑色窗口的情况下启动该过程?
看来不可能。但是可以从 访问它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'])
Run Code Online (Sandbox Code Playgroud)