How to run python in bash scripts on mac

Viewed 25

I have python3 installed in my mac and I have alias python='python3' in my .zshrc file.

I have a bash script looks like:

#!/bin/bash
python -c "print(123)"

But running the above script does not recognize python. How can I let bash recognize python without changing the script file?

I added alias python='python3' to .bashrc and .bash_profile, but it didn't work.

1 Answers

Basically, you can't. Aliases are not expanded in non-interactive shell (that is in scripts).

If a slight modification of your script is acceptable, you could add

shopt -s expand_aliases
alias python=python3

on top of them. (shopt -s expand_aliases change the "do no expand aliases since non-interactive" behavior. And then, you still need to create the alias)

Otherwise, if you really can't alter in any way your script, you could do as tjm suggested: create a python symlink someplace, and ensure that this place is sooner in the PATH than any other "python" that maybe in the PATH.

Just to demonstrate

mkdir /tmp/myextrabin
ln -s $(which python3) /tmp/myextrabin/python
PATH=/tmp/myextrabin:${PATH} ./script.sh

runs script.sh with python meaning whatever python3 means to the caller.

Related