skip to Main Content

I am trying to run a Python program through a Bash script. When I execute the python file by shell it works with no problem, but when I try to execute the script, the python keyword is not recognized.

I have a fresh Ubuntu 23.10 installation and I added, on top of the ~/.bashrc file, the following line:

alias python=python3

How to solve this problem?

Toy example

For sake of simplicity I made a toy example that displays the same behavior.

I have an hello-world.py file, whose content is simply

print("Hello World!")

If I run it with the shell ($ python hello-world.py), it works smoothly:

Hello World!

Now I created a script start.sh whose content is:

#!/bin/bash

python hello-world.py

But if I execute it $ ./start.sh I get the following error:

./start.sh: line 3: python: command not found

2

Answers


  1. So, the issue is that your shebang isn’t running bash as a login shell (which is pretty normal). You are aliasing python to python3 in your .bashrc, but that will only get run in a login shell. So try adding:

    #!/bin/bash -l 
    

    to your shebang.

    Although, to be clear, I would consider this a hack. I would suggest that ideally you just use python3 in the shell script.

    Or, create a symlink. If you are on ubuntu, you can use python-is-python3:

    https://packages.ubuntu.com/focal/python-is-python3

    Login or Signup to reply.
  2. .bashrc is not sourced when running noninteractive shell.

    Aliases are disabled in noninteractive shell (by default).

    A script is noninteractive, so these settings are ignored.

    Refer to bash documentation on startup files.

    how to solve it?

    Create a symlink in a directory added to PATH with the name python that links to python3 executable. For example /usr/local/bin or ~/.local/bin.

    Use your linux distribution specific settings, like apt-get install python-is-python3.

    Either way, use python3 in your scripts anyway.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search