Putting python directory in the path

I added this to .bashrc so I can run pythons scripts from any dir.
export PATH="/home/andy/Python/:$PATH"

echo $PATH
/home/andy/Python/:/home/andy/.local/bin:/home/andy/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

But I get this when I run python3.6 hello.py
python3.6: can't open file 'hello.py': [Errno 2] No such file or directory

I found something strange.
I put a bash script in my python directory and then tried to run it from another directory not in the path.

It ran ok ?

That’s because you’re not running a “command” called hello.py. You’re
running the command python3.6 and handing it the arguments hello.py,
which is a file for it to open and process. Being a Python interpreter
that processing involves parsing Python code and running it. The shell
is using $PATH to find the command python3.6, not the file hello.py
(about which it does not care - that is the command’s purview).

I presume hello.py is in /home/andy/Python. To make it a command you
need to:

  • chmod +rx hello.py to make it readable and executable

  • ensure the script starts with a shebang line:

    #!/usr/bin/python3.6

  • invoke it as just hello.py, not python3.6 hello.py

Conventionally we do not leave the extension (eg .py) on scripts; the
shebang line controls what program runs the script and therefore what
language is used.

So a script commencing with:

 #!/bin/sh

isa shell script (run by the executable /bin/sh), and one commencing:

 #!/usr/bin/python3.6

is a Python script to be run by the executable /usr/bin/python3.6.

The reason for the two permissions r (readable) and x (executable)
is that a file needs to be executable to be used by $PATH i.e. it is
marks as being a “command” and because for a -script_ to run, the
interpreter you specify (the shell, Python, whatever) is actually
invoked and opens the file itself for processing. So it needs read
permission.

There’s no real reason you couldn’t put Python scripts which you intend
to use as commands (they’re stable and work and are useful to you) in
your ~/bin directory. Your call of course.

Cheers,
Cameron Simpson cs@cskk.id.au

Thanks Cameron Simpson.

chmod +rx is a simple fix.

I could put them in ~/bin but I wanted a dedicated directory for the scripts.