"Open with ..." file on Windows with python application

I am trying to figure out how to get python to open a file when the user right-clicks on the file and selects "Open With". For example, I want the user to right-click on a text file and select my program so that my program can process the text file. Is the text file name somehow passed to my program? Thanks.

+6
source share
3 answers

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

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

+3
source

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

 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 replace HKEY_LOCAL_MACHINE if you are installing a machine language. * There are also version conventions that you can probably ignore. The MSDN section in File Types contains more detailed information.

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

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

The key value does not matter if the name exactly matches your ProgId.


* Please note that HKEY_CLASSES_ROOT is actually a fake key that "contains" a combination of both HKLM\Software\Classes and HKCU\Software\Classes ; if you are writing to the registry, you must select one of the actual keys. You do not need to raise to set to HKEY_CURRENT_USER .

0
source

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

0
source

Source: https://habr.com/ru/post/900478/


All Articles