gilesjohn gilesjohn - 1 year ago 104
Python Question

Using "Open with" on a text file with a python application

I've been looking for a way to open a text file with a text editor I made with python, and assumed it had something to do with system arguments, so made a simple application which would write the arguments sent by the system to a text window, and used "open with" on the text file and application, but the only argument was the path of the application. Many questions similar to mine have been answered on here but none of the answers have worked for me. How would I do this?

Thanks for any responses.
(I'm using OS X 10.9.5, with python 2.7)

Tried code:

from Tkinter import *
import sys, time
root = Tk()
text = Text(root)
text.pack(side=TOP, fill="both", expand=True)
text.insert(END, sys.argv)
for x in xrange(len(sys.argv)):

Displayed text:


Answer Source

If I understand your question correctly, you are talking about opening a file with the Finder's Open with context menu when clicking on a file. If so, it's probably a duplicate of MacOSX - File extension associate with application - Programatically. The standard way is to create an OS X app bundle (for Python programs, you can use py2app to do that) and then set proper key type in its Info.plist. That's assuming your text editor is a true GUI app (uses Tkinter or Cocoa or whatever) and not just a program that runs in a shell terminal window (in for example). In that case, you might be able to create a simple wrapper app (even using AppleScript or Automator and modifying its Info.plist as above) to launch your Python program in a terminal window and pass in the file name from the open event. To properly handle multiple files opened at different times would require more work.

UPDATE: as you have clarified, you are using Python Tkinter and a real GUI app. The native OS X Tk implementation provides an Apple Event handler to allow you to process Apple Events like Open Document. The support is described in tcl terms in the Tcl/Tk documentation so you need to translate it to Python but it's very straightforward. Python's IDLE app has an example of one, see, for instance, addOpenEventSupport in For simple apps using py2app, you could instead use py2app's argv emulation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download