Search code examples
pythonwindowssubprocesspopenexplorer

How to Search in Windows with Python subprocess


  • How can subprocess be used to open a specific local or network directory in Windows File Explorer, and search for image file names with a specific string.
  • In this case, the requirement is:
    • Only display specific images (out of many), in File Explorer, for a quick visual verification.
  • For this purpose, I am not interested in knowing how to search Windows with os or pathlib. Those methods are clearly explained in Find a file in python

enter image description here


Solution

    • Note: Search locations must be indexed by Windows
      • Look in Control Panel for Indexing Options
    import subprocess
    
    query_string = 'file_name.png'
    local_path = r'C:\Users\your_name\Pictures' # r is raw for dealing with backslashes
    network_path = r'\\your\network\fold\path'
    
    # for a network location
    subprocess.Popen(f'explorer /root,"search-ms:query={query_string}&crumb=location:{network_path}&"')
    
    #for a local folder
    subprocess.Popen(f'explorer /root,"search-ms:query={query_string}&crumb=folder:{local_path}&"')
    
    1. subprocess.Popen is from the Python standard library Subprocess management.
    2. search-ms:parameter=value[&parameter=value]& is from MSDN Getting started with parameter-value arguments.
    • Parameter-value arguments can be configured in a variety ways not exclusive to the way shown here. For example, folder will only locate local folders, but location will work for network and local folders.
    1. f'some_string {variable}' is from PEP498: Formatted String Literals.
    2. explorer & /root are Windows commands.