Launch a GUI process without spawning a black shell window
Asked Answered
S

1

6

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?

Southey answered 9/11, 2012 at 14:49 Comment(1)
Surprising : I tried with WinExec and ShellExec on C/C++ code and it gives my the same behaviour.Peirsen
S
3

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'])
Southey answered 9/11, 2012 at 19:42 Comment(1)
Can you have a look at this question ? thanks !!!#19851613Hector

© 2022 - 2024 — McMap. All rights reserved.