I'm having to update a legacy Python 2 program and as such I figured I'd use the shebang line to confirm the correct version of Python is used in certain contexts. I haven't used the shebang line before and apparently I'm unclear on it's purpose and action.
Currently I'm using a computer with a relatively fresh Ubuntu 18.04.5 install and Python 2 is not installed yet (Python 3 is installed). I made a test script named test.py
with the following contents:
#!/usr/bin/env python2
import sys
print(sys.version)
and ran it as follows and received the following results:
$ python3 test.py
3.6.9 (default, Oct 8 2020, 12:12:24)
[GCC 8.4.0]
As you can see the program ran and printed the version, which I don't understand. Is this really the expected behavior? Since Python 2 is not installed I would have expected a result along the lines of:
ERROR: Python 2 is not installed
Also I have a 2nd question, but before I ask that I should mention I did the following:
$ chmod +x test.py
$ ./test.py
and received the following result:
/usr/bin/env: ‘python2’: No such file or directory
Which would be my expected results given the script and these commands, so at least my faith in the shebang line is partially restored, which brings me to my second question. If I modify test.py
so the shebang is no longer the first line as follows:
# test.py
#!/usr/bin/env python2
import sys
print(sys.version)
And then run it:
$ ./test.py
The terminal hangs for about 30 seconds, then says this:
import-im6.q16: not authorized `sys' @ error/constitute.c/WriteImage/1037.
./test.py: line 4: syntax error near unexpected token `sys.version'
./test.py: line 4: `print(sys.version)'
Which is exactly the same result I get as if I remove the shebang line entirely. Is this the expected behavior, i.e. if the shebang line is not the first line but is otherwise correct is it supposed to do nothing?