12

How can I run a python script in Terminal on Mac without using the "python" keyword, without having to edit my existing python files?

Right now I have to do this: python script.py

What I like to do is this: script.py

3 Answers 3

19

Add a shebang:

#!/usr/bin/python

or

#!/usr/bin/env python

I prefer the second one, since Python can be anywhere like /usr/bin/python, /usr/local/bin/python etc. and second one ensure that you don't have to keep editing the shebang.

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

Sign up to request clarification or add additional context in comments.

1 Comment

Will this trick work on the windows machine as well ?
15

in your python script add this as your first line

#!/usr/bin/python

then in terminal do this chmod +x ./yourpythonscript.py

then from terminal execute as ./yourpythonscript.py

3 Comments

@mofle nope sorry you can't make a file executable in unix system without specifying what file will execute it
I dont know about how but it might be possible on a Mac to associate an extension or a mime type to a handler (e.g. open all files of type .py with python) etc. Then you can do it without modifying your source files.
Actually, you can make a text file executable - but the system will then use your shell (probably bash) to execute it. Also, #! /usr/bin/env python is marginally more portable as it doesn't hardcode where python is.
6

Try ./script.py instead of script.py ... or ensure your current directory is in your path and script.py should work....

1 Comment

thanks, this helped. I was trying to run with just script.py in the command line and it was giving me command not found.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.