Search code examples
pythonmacosanacondaautomatorfinder

running all python files on MAC with anaconda environment


I'd like to start all files with the extension "py" from the finder in MAC using anaconda environment, just with clicking on the file. Using the terminal with "python myfile.py" runs fine, but how can I start this directly with clicking on the file "myfile.py" within the finder.


Solution

  • You can do this with Automator:

    1. Start up Automator
    2. Choose application
    3. In the Actions bar, select Library, and search for Shell
    4. Drag "Run Shell Script" to the right pane.
    5. Change pass input to "as arguments"
    6. Change the script to

      for f in "$@" do python "$f" done

    7. Save it (possibly in the application folder, but can be anywhere) as Python.app

    8. Now if you want .py files to always launch with python:

      Select a .py file File -> Get Info In the Open with selection, choose Other, and select the Python.app you created. Click Change All


    You may also have to set the shebang for it to pick your virtualenv:

    If you want to run it from the terminal without using the python command, you can set the shebang to your anaconda environment as below:

    #!/usr/bin/python <- ADD Your Anaconda environment path here
    

    then in terminal do this:

    chmod +x ./myfile.py
    

    And then you can just execute it as ./myfile.py if it is executable.