Python inspect.getcomments(module) 如果它是一个 shebang,则不会返回第一个注释



当Python文件包含shebang(#!blabla)时,来自模块inspect的函数getcomments不会返回它。我该怎么做才能从模块对象中获得shebang?

shebang只有在它是文件的第一行时才有效。。。所以,看起来你可以做一些类似的事情:

import module
fname = module.__file__
with open(fname) as fin:
    shebang = next(fin)

当然,我已经跳过了一堆微妙之处。。。(确保第一行实际上是一个注释,确保我们获取了一个.py文件而不是.pyc文件,等等)。如果你想让它更健壮,那么这些检查和替换应该足够容易。

而且,我想使用__file__魔术的另一种选择是使用inspect.getsourcelines:

 shebang = inspect.getsourcelines(module)[0]
 if not shebang.startswith('#!'):
    pass #Not a shebang :)

最新更新