Folau
Folau

Reputation: 257

Python script runs on command line but not from .sh file

I'm attempting to create a .sh file to batch a number of runs of a neural network on Python whilst on holidays.

At the moment I have been calling this from the command line:

python neural_network_trainer.py [args]

I now have a .sh script written:

#!/bin/bash

python neural_network_trainer.py [args]

# Repeated with varied args

That I am attempting to call in the same terminal as the original command line was running:

./august_hols.sh

I get the following error:

File "/data/Python-3.6.9/lib/python3.6/site.py", line 177
file=sys.stderr)
    ^
SyntaxError: invalid syntax

Where the Python install is in /data (for reasons).

Running which on the command line reports the correct Python directory set via an alias in ~/.bashrc:

alias python=/data/Python-3.6.9/bin/python3

But running which between the Bash shebang and the first python call reports /bin/python.

I've attempted to set the alias again at the start of the .sh script to no avail. I'm scratching my head as this is exact process I have used elsewhere, albeit not on this precise PC. I can copy the exact command from the top of the bash file into the terminal and it runs fine, try and call ./august_hols.sh and get the above Python error.

Where is Bash getting that path from, and why is it not using my expected route through ~/.bashrc?

Upvotes: 0

Views: 2899

Answers (5)

Waket Zheng
Waket Zheng

Reputation: 6331

How about this:

#!/bin/bash

/data/Python-3.6.9/bin/python3 neural_network_trainer.py [args]

# Repeated with varied args

Upvotes: 0

pyr0
pyr0

Reputation: 377

A maybe more nasty solution

mapfile < <(declare -p | grep -m 1 BASH_ALIASES) && bash script.sh "${MAPFILE[@]}"

within your script you will need

shopt -s expand_aliases
eval $1
echo ${BASH_ALIASES[python]}
python --version

Upvotes: 0

hehaoqian
hehaoqian

Reputation: 166

Bash sub-shell does not inherit alias in the main shell

You can source the script (run in the main shell), instead of execute it (run in the sub-shell)

source script.sh

EDIT:

Solution 2:

Run bash as the login shell so ~/.bashrc is executed, so your alias is loaded before your script.

The subshell needs to be interactive to enable alias, because alias is enabled by default only for interactive shell, but script is non-interactive by default.

bash --login -i script.sh

Solution 3:

Similar to above, except alias is enabled explicitly

bash --login -O expand_aliases script.sh

Upvotes: 3

NinjaGaiden
NinjaGaiden

Reputation: 3146

In your .sh

Do this

#!/usr/bin/env bash
export PATH=/data/Python-3.6.9/bin:$PATH
exec python neural_network_trainer.py "$@"

Aliases are tricky.

Upvotes: 0

Georgina Skibinski
Georgina Skibinski

Reputation: 13387

Have you tried:

python=/data/Python-3.6.9/bin/python3 ./[your_bash].sh

Upvotes: 0

Related Questions