Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't run Python .py files from terminal on Mac

Tags:

python

I just downloaded Python 3.2 to Mac OS 10.6 environment. I'm new to programming and am trying to run my first stand-alone .py file, but I keep getting an error message saying "no such directory or file." The name of the file is "script1.py" and I saved it to /Users/billp/Documents. When I open the Terminal to run the file I type:

python script1.py

I've also tried adding this line to the beginning of the script:

#!/usr/local/bin/python

As well as this one:

#!/usr/bin/env python

Yet, I keep getting the same error message. Any help would be greatly appreciated.

like image 904
Bill P Avatar asked Oct 21 '11 22:10

Bill P


People also ask

How do I run a .PY file 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.

Why my Python file is not running on terminal?

As you can see, when you get an error like this, this is a problem with the directory. The best thing to do in this case is to actually locate your file, and copy and paste the file path from there rather than type in the address in the terminal / command prompt.

How do I run a Python .PY file in terminal?

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!


1 Answers

Make sure you are in the right working directory after opening terminal. Type

cd /Users/billp/Documents/

(use tab to autocomplete)

then

python ./script1.py

This way you are launching python executable and passing it path to your file as the first argument. The shebang #! line you mentioned allows you to launch your script directly, like this: ./script1.py, but you need to mark the file as executable chmod +x script1.py and provide path to interpreter (python) after the shebang. #!/usr/bin/env python references your default python installation.

The ./ stands for current directory. By default when you type script1.py your shell (which is the thing that you type commands into, through the terminal) would look for executable file in special folders listed in PATH env variable. script1.py is not usually there, so you would see -bash: script1.py: command not found. python, on the other hand is on the PATH so it should work.

like image 95
lormus Avatar answered Oct 06 '22 01:10

lormus