对于实用程序脚本中的日志记录设置,将日志文件名设置为导入模块的名称会很有用:
foo.py:
import bar
if __name__ == '__main__':
bar.setup_logging()
bar.py:
def setup_logging():
[...]
logging.basicConfig(filename=???, [...])
致电foo.py
时应打印foo
(或foo.py
)。
答案 0 :(得分:4)
frm = inspect.stack()[1]
#Now, frm contains a tuple of frame object, code path, code line etc...
mod = inspect.getmodule(frm[0])
#pass the frame object to get the module object and print its name prop
print '[%s] %s' % (mod.__name__, msg)
答案 1 :(得分:0)
@MadhavanKumar走在正确的轨道上:
$ cat lib/bar.py
def setup_logging():
print os.path.basename(inspect.stack()[1][1])
$ python lib/foo.py
foo