简体   繁体   中英

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

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM