6

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)

コードは正常に機能しますが、非シェルモード(を使用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のない​​シェル実行可能ファイルで正常に機能します。ただし、起動しませんexplorer.exe

以前に黒いウィンドウを生成せずにプロセスを起動するにはどうすればよいですか?

4

1 に答える 1

3

それは不可能のようです。ただし、からアクセスできます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'])
于 2012-11-09T19:42:11.980 に答える