The shebang is only valid if it is the first line of the file ... So, it seems like you could do something like:
import module
fname = module.__file__
with open(fname) as fin:
shebang = next(fin)
Of course, I've jumped over a bunch of subtleties ... (making sure the first line is actually a comment, making sure that we've grabbed a .py
file instead of a .pyc
file, etc.). Those checks and substitutions should be easy enough to make though if you want to make it more robust.
And, I suppose an alternative to using __file__
magic would be to use inspect.getsourcelines
:
shebang = inspect.getsourcelines(module)[0]
if not shebang.startswith('#!'):
pass #Not a shebang :)