Python inspect.getcomments(module) doesn't return the first comment if it's a shebang

StackOverflow https://stackoverflow.com/questions/17827880

  •  04-06-2022
  •  | 
  •  

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?

有帮助吗?

解决方案

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 :)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top