0

I have been putting my code on github, but I've run into an implementation snag. I run the same code on many computers (including a computer that I do not have root access on).

One piece of code (a bash script) calls some python code like:

python somecode.py

The shell will run the correct version of python, but it won't find somecode.py.

What I've tried:

Fail #1: I tried to add both the directory which contains somecode.py and the full path to the file to the PATH; to no avail. [Errno 2] No such file or directory

Fail #2: I can make it work for one computer ONLY if I add the full path to the correct version of python in the top line:

#!/usr/local/cool/python/version/location

However this breaks it running on any other computer.

Fail #3: I can also make it work if I make the bash script say:

python /full/path/to/github/place/somecode.py

but again, this only works for ONE computer because the paths are different for different computers.

What I really want to do: I want to be able to use the same code (both bash script and somecode.py) on multiple computers.

Any suggestions about how to do this properly is welcome. Thanks!

Solution

Added:

#!/usr/bin/env python

To the top of my somecode.py code;

mv somecode.py somecode
chmod +x somecode

Make sure PATH has /full/path/to/directory/with/somecode.

Bash script now says only:

somecode

and it works.

JBWhitmore
  • 10,116
  • 9
  • 33
  • 49

2 Answers2

5

For problem #2 try

#!/usr/bin/env python

though it may find different versions of Python on different machines, but as long as that's not a problem this should fix that particular problem

See this SO question Python deployment and /usr/bin/env portability too. And this post by Alex Martelli re use of this.

Community
  • 1
  • 1
Levon
  • 118,296
  • 31
  • 184
  • 178
  • @JBWhitmore How does that fix your `No Such File or Directory` problem? – Tim Pote Jun 25 '12 at 13:57
  • @Tim, figured it was long enough to append how I fixed it to the question. The "no such file" error was just when I tried that particular workaround to the problem. It now works just fine. – JBWhitmore Jun 25 '12 at 15:46
  • 1
    @JBWhitmore Ah, I misunderstood. The "no such file" error was a result of your shabang path, not of not finding the `somecode.py`. Alright then, congrats and happy coding! – Tim Pote Jun 25 '12 at 16:19
2

If you say python somefile.py then it will take the location of somefile.py as the current directory, not from $PATH. It will take the location of python from $PATH.

If you say somefile.py then it will take the location of somefile.py from $PATH, and the location of python from the #! line of your python script, which can use the PATH if you follow @Levon's suggestion.

cdarke
  • 37,606
  • 5
  • 69
  • 77