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:
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.
is it possible to replace the
#!/usr/bin/env python3at 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" "$@"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With