Search code examples
pythonmacosfinder

Python script that can run from OSX Finder and Windows Explorer


I have a bunch of useful Python3 scripts that I use in different OS environments. They run fine when called from the terminal but I want to run them from both Windows Explorer and OSX Finder. In Windows, that is not an issue as the *.py files get associated with the installed interpreter.

For OSX, I am having some problems. I tried using the shebang line.

#!/usr/bin/python3

But Finder doesn't recognize it as a script. How do I make Finder recognize *.py files as scripts? I am interested in maximum portability with as few OS modifications as possible.

Also I explicitly specified the interpreter location above. It will be in different locations for different OSes. Is there a way to make it multi-OS so that if it doesn't find it in one location, it will try another? Say if I want to run it from one of Ubuntu's GUI File Manager.

EDIT: Here's more info on my use case. I want to go to a new computer and git clone my repo of Python3 scripts and be able to run them from within the GUI file manager with minimal changes to the new computer.


Solution

  • To make the script more portable use #!/usr/bin/env python3 as shebang. Side effect will be that it will run the first python3 interpreter it finds in the $PATH (Unix StackExchange question on that subject)


    To run the script from the finder try to chmod the file. i.e. chmod +x FILE


    Found another possibility here: Link to the Blog

    1. Make this the first line of your Python script "#!/usr/bin/env python"
    2. Change the extension of the script file to ".command" i.e. my_python_script.command
    3. In Terminal make the Python script file executable by running "chmod +x my_python_script.command"
    4. Now when you double click the Python script in Finder it will open a terminal window and run.

    Alternative I found would be this but it needs system modification: Superuser question