Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a bash script that returns a Python interpreter replace the shebang?

I've got some Python scripts that are now being run by a wide variety of folks across multiple test platforms. This creates a problem for 2 reasons:

  1. The python3 path is not the same across all the testers, and
  2. Not all of the people running the scripts have a path to Python set in $PATH.

Because of (1) I can't hard-code the shebang since its tester dependent and because of (2) #!/usr/bin/env python3 isn't guaranteed to work if placed at the top of Python file.

I know that the python3 interpreter is going to be in one of a few locations across the testers. So what I'm wondering, is it possible to replace the #!/usr/bin/env python3 at the top of the Python file with a call to a bash shell script that looks for the python location and then "sets" it for the script? If that's not possible, then the rest of this is moot.

I created a bash script that does look through the possible locations until it finds the interpreter, but what I don't know how to do is return it in the top of a Python file.

For example, I created a basic python file (shebang.py)

#!./pyshebang.sh

print("Hello World")

pyshebang.sh does 2 things, it appends the found python path to PATH, and echo's back that path to the interpreter. If I run the python script above, stdout gets the echo from the bash script, but not the print from the python script.

like image 832
milnuts Avatar asked Jan 27 '26 21:01

milnuts


1 Answers

is it possible to replace the #!/usr/bin/env python3 at the top of the Python file with a call to a bash shell script that looks for the python location and then "sets" it for the script?

Yes, of course. That's effectively what /usr/bin/env python3 does. There's nothing magic about that particular command; it and variations on it just happen to be broadly useful.

I created a bash script that does look through the possible locations until it finds the interpreter, but what I don't know how to do is return it in the top of a Python file.

You have a misunderstanding about what's happening. A shebang line does not result in a substitution into the script. Rather, it results in the specified line being executed as a command, with the path to the original script and the arguments to it appended as an additional arguments.

Thus, your pyshebang.sh should have a general form along these lines:

#!/bin/bash
# Note: the above shebang line is not a special case

# ... find Python ...

MY_PYTHON=/the/python/I/discovered

# Execute the discovered Python, passing it all the arguments this
# script received
exec "$MY_PYTHON" "$@"
like image 190
John Bollinger Avatar answered Jan 30 '26 13:01

John Bollinger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!