'"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 on a text file and to select my program so that my program can process the text file. Is the name of the text file passed into my program someway? Thanks.



Solution 1:[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:[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:[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.

Solution 4:[4]

@roy cai's answer is right, it just needs some modifications.

According to here, the someprogram.bat should contain

start someprogram.py(w) %*

Just give your cmdline args to the bat file. The %* takes up all the cmdline args, according to here from here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Roy Cai
Solution 2 Giacomo Lacava
Solution 3 Zooba
Solution 4 Great Owl