Skip to content Skip to sidebar Skip to footer

"open With..." A File On Windows, With A Python Application

I am trying to figure out how to make a python program open a file when a user right clicks on the file and selects 'Open With'. For example, I want a user to be able right click o

Solution 1:

My approach is to use a redirect .bat file containing python someprogram.py %1. The %1 passes the file path into the python script which can be accessed with from sys import argv argv[1]

Solution 2:

The problem with this approach is that your .py file is not an executable; Windows will pass the text file as parameter to the .py file, but the .py file itself will not do anything, since it's not an executable file.

What you can do is compile your script with py2exe to get an actual executable, which you can actually specify in the "Open With..." screen (you could even register it as the default for any *.foo file). The path to the .foo file being passed should be sys.argv[1] in your script.

Solution 3:

First you will need to register your script to run with Python under a ProgId in the registry. At a minimum, you will need the open verb defined:

HKEY_CURRENT_USER\Software\Classes\MyApp.ext\
  (Default) = "Friendly Name"
  DefaultIcon\
    (Default) = "path to .ico file"
  shell\
    open\
      command\
        (Default) = 'path\python.exe "path\to\your\script.py""%L"'

You can substitute HKEY_LOCAL_MACHINE if you are installing machine-wide.* There are also versioning conventions that you can probably ignore. The MSDN section on File Types has more detailed information.

The second step is to add your ProgId to the OpenWithProdIds key of the extension you want to appear in the list for:

HKEY_CURRENT_USER\Software\Classes\.ext\OpenWithProgIds
  MyApp.ext = None

The value of the key does not matter, as long as the name matches your ProgId exactly.


*Note that HKEY_CLASSES_ROOT is actually a fake key that 'contains' a union of both HKLM\Software\Classes and HKCU\Software\Classes; if you're writing to the registry, you should choose one of the actual keys. You don't need to elevate to install into HKEY_CURRENT_USER.

Post a Comment for ""open With..." A File On Windows, With A Python Application"