Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python3 won't run from mac shell script

I am trying to use Automator on macOS 10.12 to launch a Python 3 script. The script works just fine when I run it from the terminal with the command: python3 my_script.py.

Automator has a "Run Shell Script" function that uses the /bin/bash shell. The shell will run scripts with the command: python my_script.py, but this only seems to work for scripts written in Python 2.7.

My script starts with #!/usr/bin/env python3, which I thought would direct the shell to the correct python interpreter, but that doesn't seem to be the case.

As a workaround, I can get the script to run if I insert the full path to the python interpreter: /Library/Frameworks/Python.framework/Versions/3.5/bin/python3, but I see this as suboptimal because the commands might not work if/when I update to Python 3.6.

Is there a better way to direct the /bin/bash shell to run Python3 scripts?

like image 340
Slipup Avatar asked Oct 29 '22 14:10

Slipup


People also ask

How do I run a Python script in terminal Mac?

On a Mac system, it is very straight-forward. All you need to do is open Launchpad and search for Terminal , and in the terminal, type Python and boom, it will give you an output with the Python version.

How do I run a python3 script?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World! If everything works okay, after you press Enter , you'll see the phrase Hello World!


2 Answers

Since you have the shebang line, you can do ./my_script.py and it should run with Python 3.

like image 85
Aryaman Avatar answered Nov 15 '22 07:11

Aryaman


You can install Python 3 via Homebrew with brew install python3 and use #!/usr/local/bin/python3 as your shebang.

Not a perfect solution but still better than using the full path of the interpreter.

like image 44
xilopaint Avatar answered Nov 15 '22 07:11

xilopaint