Associate file extension to python script, so that I can open the file by double click, in windows

倖福魔咒の 提交于 2019-11-27 06:52:40

问题


I want to do the following:

  1. Save numeric data in a CSV-like formatting, with a ".foo" extension;
  2. Associate the ".foo" file extension with some python script, which in turns opens the .foo file, reads its content, and plots something with a plotting library (matplotlib most probably).

The use-case would be: double-click the file, and its respective plot pops up right away.

I wonder how I should write a python script in order to do that. Besides, the windows "open with" dialog only allows me to choose executables (*.exe). If I choose "fooOpener.py", it doesn't work.


回答1:


This isn't really a programming question, but what you need to do is to figure out how to get the Python executable into the registry key that opens your data file.

For example, I created a little Python script called opener.py that looks like this:

import sys
print(sys.argv)
input()

Then I created a testfile.foo and used the "change" button in that file's property dialog to choose opener.py. (You can do this if you click Browse and change the Open With dialog's file filter to "All Files".)

Of course this didn't work (as you noticed). So I opened regedit and searched for opener.py and found it at the following registry key:

HKEY_CURRENT_USER\Software\Classes\Applications\opener.py\shell\open\command

The default value of this key was "C:\opener.py" %1. I changed it to python "C:\opener.py" %1. It worked!

Long story short, to do this properly you need to custom-edit the registry. Actually setting up the file association is more complex than just editing that one key (you have to also indicate that .foo is associated with opener.py).

An alternative approach would be to turn your Python script into a standalone executable using one of the several tools available for that purpose, or write a small executable in C that launches the script.



来源:https://stackoverflow.com/questions/29041571/associate-file-extension-to-python-script-so-that-i-can-open-the-file-by-double

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!