Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open specific file type with Python script?

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.

Is this possible to do in Win and/or OS X? The application is a PySide app if that matters.

like image 592
c00kiemonster Avatar asked Jan 01 '12 14:01

c00kiemonster


People also ask

Can Python read any file type?

There are two types of files that can be handled in python, normal text files and binary files (written in binary language, 0s, and 1s). Text files: In this type of file, Each line of text is terminated with a special character called EOL (End of Line), which is the new line character ('\n') in python by default.


1 Answers

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 "$@"

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.

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

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 %*

The %* expands to all arguments.

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.

like image 113
Scott H Avatar answered Nov 16 '22 02:11

Scott H