I want to open Windows Explorer and select a specific file.
This is the API: explorer /select,"PATH"
. Therefore resulting in the following code (using python 2.7):
import os
PATH = r"G:\testing\189.mp3"
cmd = r'explorer /select,"%s"' % PATH
os.system(cmd)
The code works fine, but when I switch to non-shell mode (with pythonw
), a black shell window appears for a moment before the explorer is launched.
This is to be expected with os.system
. I've created the following function to launch processes without spawning a window:
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
This works fine for shell executables with no GUI. However it won't launch explorer.exe
.
How can I launch the process without spawning a black window before?
It doesn't seem to be possible. However it can be accessed from the win32api
. I've used the code found 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'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With