将文件扩展名与python脚本相关联,以便我可以在Windows中通过双击打开文件 [英] Associate file extension to python script, so that I can open the file by double click, in windows

查看:87
本文介绍了将文件扩展名与python脚本相关联,以便我可以在Windows中通过双击打开文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要执行以下操作:

  1. 以类似于CSV的格式保存数字数据,扩展名为".foo";
  2. 将".foo"文件扩展名与某些python脚本相关联,这反过来会打开.foo文件,读取其内容,并使用绘图库(最有可能是matplotlib)对某些内容进行绘图.

用例为:双击文件,并立即弹出其对应的图.

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

我想知道我应该如何编写python脚本来做到这一点. 此外,Windows打开方式"对话框仅允许我选择可执行文件(* .exe).如果我选择"fooOpener.py",则无法使用.

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.

推荐答案

这实际上不是编程问题,但是您需要做的是弄清楚如何将Python可执行文件放入打开数据的注册表项中文件.

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.

例如,我创建了一个名为opener.py的小Python脚本,如下所示:

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

import sys
print(sys.argv)
input()

然后,我创建了一个testfile.foo,并使用该文件的属性对话框中的更改"按钮来选择opener.py. (如果您单击浏览"并将打开方式"对话框的文件过滤器更改为所有文件",则可以执行此操作.)

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".)

当然这是行不通的(如您所注意到的).因此,我打开了regedit并搜索了opener.py,并在以下注册表项中找到了它:

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

此键的默认值为"C:\opener.py" %1.我将其更改为python "C:\opener.py" %1.奏效了!

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

长话短说,要正确执行此操作,您需要自定义编辑注册表.实际上,设置文件关联比仅编辑一个键要复杂得多(您还必须指出.fooopener.py相关联).

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

另一种方法是使用为此目的可用的几种工具之一将您的Python脚本转换为独立的可执行文件,或者用C编写一个小的可执行文件来启动脚本.

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.

这篇关于将文件扩展名与python脚本相关联,以便我可以在Windows中通过双击打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆