In the Pyenv project, we've had a peculiar problem.
We are substituting python
(and python*
) with our Bash scripts ("shims") that select a Python executable to run at runtime.
Now, some users wish to use a special selection logic when a Python script is run as path/to/script.py
. The problem is, this logic should NOT apply if the script is instead run as <python> path/to/script.py
!
Is there a way to reliably distinguish these two cases?
I wasn't able to find anything: depending on the way command line arguments are formulated in the 2nd case, the exact same command line could be executed in both cases:
(the Bash script given is not a real shim, just a demonstration example to showcase what our logic sees and does)
$ cat python3
#!/bin/bash
echo "'$0'"
for a in "$@"; do
echo "'$a'"
done
# need to do the detection here
exec python3 "$@"
$ cat t.py
#!/home/vmuser/python3
import sys
print(sys.argv)
$ $PWD/t.py
'/home/vmuser/python3'
'/home/vmuser/t.py'
['/home/vmuser/t.py']
$ $PWD/python3 $PWD/t.py
'/home/vmuser/python3'
'/home/vmuser/t.py'
['/home/vmuser/t.py']
Since shebang is a Linux kernel feature -- maybe it sets some indicator that this mechanism has been used?
We've considered requiring users to use a special shebang in their Python scripts that they wish to apply the special logic to, but that idea proved unpopular because it makes those scripts unportable.