pythonwindowstkinteropen-with

How to make a program that can be opened with a file? (python)


I was making a program that opens a file and does a few things to it, and I wondered if there was a way that you could click on a file, and it would open it in the program, instead of going into the program, clicking open, and navigation through the files to find it, or just a way where you can click "Open With..." and select your program. Here is the code if it helps:

from tkinter import *
from tkinter import filedialog
from subprocess import *
import os

root = Tk()
root.title("Snake converter")
def open_file():

    filename = filedialog.askopenfilename(filetypes = (("Snake files", "*.sim"),("Python Files", "*.py"),("All files", "*.*")))
    filenametmp = filename + ".tmp"
    print filename + " is being compiled. Please wait..."
    tf = open(filenametmp, "a")
    f = open(filename, "r")
    filecontents = f.read()
    tf.write("from simincmodule import *" + "\n")
    tf.write(filecontents)
    os.chdir("C:\Snake\info\Scripts")
    print os.getcwd()
    call(["pyinstaller", filenametmp])
    os.remove("C:/Snake/info/Scripts/build")
    f.close()
    tf.close()
    print "\n\n----------------------------------------------------------------------\n\nFinished compiling " + filename + ". Find the program under [filename]/[filename].exe"

openbutton = Button(root, text = "Open", width = 10, command = open_file)
openbutton.pack()

root.mainloop()

Any help or suggestion will be highly appreciated.

Thanks!


Solution

  • "Open with..." usually sends the pathname of the file to sys.argv. So at an appropriate place of your program, add this:

    if len(sys.argv) > 1:
        open_file(sys.argv[1])
    

    (As I said in the comment, you really want to let your open_file take an argument, and have another function like open_file_dialog to open the dialog.)

    That leaves the question of how to make something you can "Open with..." in the first place. If you are on Windows, you should be able to achieve finer control with file association by editing the registry: see this MSDN page for details.

    Alternatively, a quick-and-dirty way to do it is to make a .bat script that takes an argument and passes it to your python program. I remember doing this some time ago, but I haven't used Windows seriously for a long time, so I can't tell you how to write the script right off my head.