【问题标题】:How to get current script filename or path in python when instantiate a class?实例化类时如何在python中获取当前脚本文件名或路径?
【发布时间】:2023-02-09 11:04:08
【问题描述】:
# utils.py
class Foo:
    def __init__():
        print(__file__)

# mod.py
from utils import Foo

foo = Foo()
# This prints /absoulte/utils.py
# the expected output is /absoulte/mod.py

是否可以使用当前文件信息而不是在不传递参数的情况下定义导入类Foo 初始化?

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    是的,可以确定使用该类的当前文件,而不是定义它的文件。您可以使用标准库中的 inspect 模块来访问有关当前堆栈帧的信息并确定文件路径。

    这是 Foo 类的更新版本,它打印使用它的文件:

    # utils.py
    import inspect
    
    class Foo:
        def __init__(self):
            frame = inspect.currentframe()
            filename = inspect.getframeinfo(frame).filename
            print(filename)
    

    这是 mod.py 中的用法:

    from utils import Foo
    
    foo = Foo()
    # This will now print /absolute/path/to/mod.py
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-21
      • 1970-01-01
      • 2011-01-28
      • 2018-04-13
      • 1970-01-01
      • 1970-01-01
      • 2014-01-05
      相关资源
      最近更新 更多