使用Python脚本打开特定的文件类型吗?
如何使Python脚本成为特定文件类型的默认应用程序(例如* .foo)?例如,当我双击Finder / Explorer中的文件时,我希望在Python脚本中打开该文件。
How can I make a Python script to be a specific file type's (e.g., *.foo) default application? As in, when I double click the file in the Finder / Explorer I want the file to open in the Python script.
在Win和/或Windows中可以这样做吗? OS X?
Is this possible to do in Win and/or OS X? The application is a PySide app if that matters.
Mac OS X
在 Mac OS X 上,您可以使用 Automator 创建一个应用程序,该应用程序调用您的python应用程序并将输入文件路径作为字符串参数传递。在应用程序工作流向导中,添加操作运行Shell脚本,选择传递输入:
作为作为参数
,然后在文本框添加:
Mac OS X
On Mac OS X you can use Automator to create an application that calls your python app and passes the input file path as a string argument. In the application workflow wizard, add action "Run Shell Script", select Pass input:
as as arguments
, and in the text box add:
python /path/to/my/app/myapp.py "$@"
$ @
会传递输入(也就是所选文件)作为字符串。只要您的脚本设置为将输入( sys.argv
)作为字符串列表处理(第一个是python应用程序路径),那么它将
The "$@"
passes along whatever arguments were in the input (aka the selected file) as strings. As long as your script is set up to deal with the input (sys.argv
) as a list of strings (the first one being the python app path), then it will work.
保存该Automator工作流程后,OS X会像对待其他任何应用程序一样对待它,并且可以将该应用程序设置为类型为 *的文件的默认设置.foo。要将 * .foo与该应用程序关联,请右键单击.foo文件,然后依次单击获取信息
,打开...:$ ... c $ c>,选择您在Automator中创建的应用,然后单击
全部更改...
按钮。
When you save that Automator workflow, it is treated by OS X like any other app, and you can set that app as the default for files of type "*.foo". To associate "*.foo" with that app, right click a .foo file, Get Info
, Open with: Other...
, choose the app you created in Automator, then click the Change All...
button.
一种类似但希望较少涉及的方法可能在Windows中可用。您可能会创建具有以下内容的批处理文件( .bat
):
A similar but hopefully less-involved approach might work in Windows. You could probably create a batch file (.bat
) with the following:
python C:\path\to\my\app\myapp.py %*
%*
会扩展到所有参数。
只要您可以将文件扩展名与此关联批处理文件,那么您可以这样做,那就是您的解决方案。但是,我还没有尝试过Windows解决方案,因此请带一点盐。另一方面,我已经测试了Mac解决方案。
As long as you can associate a file extension with that batch file, then you could do that, and that's your solution. However, I haven't tried this Windows solution, so take it with a grain of salt. The Mac solution, on the other hand, I have tested.