2

I have a python script that I want to execute from the terminal, but I don't want to use the command pythonscriptName.py, instead, I'd like to just type scriptName. Is that possible? If it is, how?

I had a look in here and here, but it doesn't work (probably because I'm on a different os).

I'm using python 2.7.9 on osx Yosemite (10.10.3).

Community
  • 1
  • 1
dccsillag
  • 919
  • 4
  • 14
  • 25
  • possible duplicate of [Calling a python script from command line without typing "python" first](http://stackoverflow.com/questions/3400381/calling-a-python-script-from-command-line-without-typing-python-first) – tripleee May 04 '15 at 18:45
  • That is run on linux – dccsillag May 04 '15 at 18:55
  • The mechanism is the same on any remotely U*x-flavored system. In fact, the environment (Bash) is exactly the same (albeit an older version on OSX). – tripleee May 05 '15 at 03:10

1 Answers1

5

Put this as the first line in your Python script:

#!/usr/bin/python

(or wherever your Python interpreter lives).

Then give the script the executable bit:

chmod +x scriptName.py

Now you should be able to execute it like ./scriptName.py. You can then put a symlink without the .py extension somewhere in your path.

cfh
  • 4,576
  • 1
  • 24
  • 34
  • What do you mean by "add a symlink"? – dccsillag May 04 '15 at 18:45
  • I tried your answer, but I'm not able, after adding the line `#!/usr/bin/python` and doing `chmod +x pythontool.py`(pythontool.py is my file), to type into the terminal `./pythontool.py` and run my file. Does this have something to do with bash? – dccsillag May 04 '15 at 20:35
  • @DCPY: Did you check that the path to the python interpreter is correct? You can type `which python` at the terminal to find out. – cfh May 04 '15 at 20:59
  • it displays `/Library/Frameworks/Python.framework/Versions/2.7/bin/python`. – dccsillag May 04 '15 at 21:09
  • @DCPY: You have to put then into the header then instead. These are basic bash things, you can read up on it. – cfh May 04 '15 at 22:02