double click a file to run python script. how to g

2019-06-07 17:52发布

问题:

I want to be able to create a program that can save text files with my own extension at the end. later the user should be able to double click on that file to run the program and open that file.

I need to know how to make the python program the default program a file opens whenever the user double click on it , and also how to get that file when the program starts running.

python 2.7 mac os x 10.6 and windows 7

edit: say as an example, i was making a paint program. the user wants to save the file he was working on. my program will save it as untitled.paint, later the user double click on untitled.paint and expects my program to open up that file.

is there a way for me to tell the operating system to open all files ending with .paint with my paint program.

I can't save it as a .jpg because that won't save the layers or anything else.

回答1:

Don't know about OSX but in Windows you can do it as follows:

  1. Create a batch file
  2. Select a file of the type you want to open "automatically", and use "Open with..." in the context menu to select the batch file as the default program to use.
  3. The batch file will get the "clicked" file passed argument 1, which you can then pass to your Python script as an argument - it then receives it as sys.argv[1].

An example using an extension ".paint" which is opened using a hypothetical python script pypaint.py may clarify things:

run_paint.bat:
@echo off
echo 'clicked file is' %1
python path_to_pypaint.py %1

py_paint.py:
import sys
print 'opening', sys.argv[1]