Opening file - Performing a function

我怕爱的太早我们不能终老 提交于 2019-12-13 09:58:46

问题


I was wondering if someone could give me a direction on how to give functions to a file... This is a bit hard to explain, so I'll try my best.
Let's say I have an application (using wxPython) and let's say that I have a file. Now this file is assigned to open with the application. So, I double-click the file and it opens the application. Now my question is, what would have to be written on the file to, for example, open up a dialog? So we double-click the file and it opens a dialog on the application?

PS: I know that I have first to associate the program with a certain file type to double-click it, but thats not the question.


回答1:


AFAIK most platforms just call the helper app with the file you clicked on as an argument, so your filepath will be in sys.argv[1]




回答2:


I think what he wants to do is associate a file extension to his application so when he opens the file by double clicking it, it sends the contents of the file to his app; in this case, display the contents within a Dialog?

If this is the case, than the first thing you would need to do (provided you are on windows) is create the appropriate file association for your file extention. This can be done through the registry and when setup correctly will open your app with the the path/filename of the file that was executed as the first argument. Ideally it is the same as executing it from the command line like:

C:\your\application.exe "C:\The\Path\To\my.file"

Now as suggested above, you would then need to use sys.argv to to obtain the arguments passed to your application, in this case C:\Path\To\my.file would be the first argument. Simply put, sys.argv is a list of arguments passed to the application; in this case the first entry sys.argv[0] will always be the path to your application, and as mentioned above, sys.argv[1] would be the path to your custom file.

Example:

import sys

myFile = sys.argv[1]
f = file(myFile, "r")
contents = f.read()
f.close()

Then you will be able to pass the variable contents to your dialog to do whatever with.



来源:https://stackoverflow.com/questions/5453782/opening-file-performing-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!