0

I outsmarted myself and created an error as a result of trying to be prepared.

On the first line of a script I placed #! /usr/bin/python and later upgraded python and installed a new module. Sure enough, the new python is now /opt/local/bin/python and I got errors. It took a bit of debugging before I found this.

Anyway, now that I have I am wondering what is the best way to run a script:

Should I:

  1. use python <myscript.py> or
  2. make it executable, add the environment on the first line, and use it from the command line ./<myscript.py>

I like 2. but upon upgrading or changing the default python, the script can break because it specifies a different install.

Then am I expected to go through all the scripts and update them?

Is there a way to make the current/default python override the one specified on line1 of the script or is there another way to make a script executable without explicitly stating which python it uses (ie, to use the default one)?

Madivad
  • 2,285
  • 4
  • 26
  • 56
  • 10
    `#!/usr/bin/env python`, see http://stackoverflow.com/questions/2429511/why-do-people-write-usr-bin-env-python-on-the-first-line-of-a-python-script – Ismail Badawi Jul 16 '13 at 00:58
  • Also see [PEP 394: The "python" Command on Unix-Like Systems](http://www.python.org/dev/peps/pep-0394/), which gives some more details. (It's mostly about Python 2 vs. 3 or 3.x vs. 3.y, and it assumes you already know the basics of shbang lines, the `env` command, and prior practice… but there's some useful info there.) – abarnert Jul 16 '13 at 01:02
  • @isbadawi: You should write that up as an answer, with some explanation (unless you think this question needs to be closed as a dup). – abarnert Jul 16 '13 at 01:03
  • @isbadawi, abarnet just beat me to it, but if you write that up as the answer, I'll check it. That was what I was after. Thanks – Madivad Jul 16 '13 at 01:03
  • Also note that this is in the official tutorial under [Executable Python Scripts](http://docs.python.org/3/tutorial/interpreter.html#executable-python-scripts). – abarnert Jul 16 '13 at 01:05
  • Thanks for that link at the top (1st comment), I did search, but not knowing what it was I was looking for, I didn't even see that post (in fact that particular post didn't come up in any of my searches—obviously not using the best search terms) – Madivad Jul 16 '13 at 01:07

1 Answers1

0

Since the mentioned stackoverflow links do not have an accepted answer. I'll answer it while giving my opinion. I think the best solution for all python scripts is #!/usr/bin/env python as changing the python that runs is as simple as modifying the PATH environment variable. This is much better than updating all scripts (assuming scripts are already this way).

Number 1 python <myscript.py> can be used first to test before PATH modification.

cforbish
  • 7,499
  • 2
  • 23
  • 29