"Open with…" a file on Windows, with a python application

Question:

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.

Asked By: osdev0

||

Answers:

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.

Answered By: Giacomo Lacava

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_USERSoftwareClassesMyApp.ext
  (Default) = "Friendly Name"
  DefaultIcon
    (Default) = "path to .ico file"
  shell
    open
      command
        (Default) = 'pathpython.exe "pathtoyourscript.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_USERSoftwareClasses.extOpenWithProgIds
  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 HKLMSoftwareClasses and HKCUSoftwareClasses; 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.

Answered By: Zooba

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]

Answered By: Roy Cai

@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.

Answered By: Great Owl
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.