0

When a Python file contains a shebang (#!blabla), the function getcomments from the module inspect doesn't return it. What can I do to get the shebang from a module object?

Dor
  • 902
  • 4
  • 24

1 Answers1

1

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 :)
mgilson
  • 300,191
  • 65
  • 633
  • 696