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