1
votes

How do I programmatically associate a file with a specific "opens with" action? That is, I am creating filename.py on a Windows computer, putting it on the desktop. I want double-clicking it to run the python intrepreter, rather than opening the text editor.

I can do this with the Properties window, but I want to do this automatically, when I create it (from another python program).

I do not want to set up a universal file extension, because I want double-clicking on .py files to result in bringing up the editor, not running the program. It is only for this particular file that I want that behavior. I can do this from the Windows GUI; I want to know how to do it programmatically.

There is no installer. The Python .py program is being created from another python program. It is being created directly in the file system with a open("filename.py").write(file_contents).

The environment is Windows 7

1
Can't you set up a universal file association, such that files with the .py extension open the python interpreter? - rst-2cv
double-clicking on the .py file usually runs the program already, doesn't edit it. Unless you're using a portable version, without file associations. so ? - Jean-François Fabre
Please be more specific about your environment. Why can't you associate the extention with Python installer? Do you need to associate system-wide or for a specific user? Why do you need to do this programmatically rather than using the "Default Programs" in Control Panel? What tools are you planning to be making the association with -- your Python program itself or something else, perhaps written in some other language? - ivan_pozdeev
Before these are addressed, the question is too vague to answer so voting to close as unclear. - ivan_pozdeev
@ivan_pozdeev, I think that the question is clear. What is vague to you? - vy32

1 Answers

1
votes

In Windows, file type associatons are per-extension. Any file with the same extension is treated the same. That's the whole idea behind them.

In principle, you can change the .py type association to run some program that would check if it runs this particular file and do a different thing.

A much easier, more manageable and predictable way to go would be to place a shortcut rather than the program onto the desktop that would run anything you need -- in this case, "path\to\python.exe" "path\to\your_program.py". That's the whole idea behind shortcuts btw. The file itself can be placed to some other user-writable place like %APPDATA%\<your_project_name> which is the standard location for application data.