Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Launch a GUI process without spawning a black shell window

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?

like image 424
iTayb Avatar asked Nov 09 '12 14:11

iTayb


1 Answers

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'])
like image 180
iTayb Avatar answered Nov 15 '22 01:11

iTayb