【问题标题】:How do I find out the path of the currently executing script? [duplicate]如何找出当前正在执行的脚本的路径? [复制]
【发布时间】:2010-10-01 10:58:45
【问题描述】:

重复:In Python, how do I get the path and name of the file that is currently executing?

我想找出当前正在执行的脚本的路径。 我已经尝试过 os.getcwd() 但它只返回我运行脚本的目录,而不是存储脚本的实际目录。

【问题讨论】:

标签: python


【解决方案1】:

在 Python 中,__file__ 标识当前 Python 文件。因此:

print "I'm inside Python file %s" % __file__

将打印当前的 Python 文件。请注意,这适用于导入的 Python 模块以及脚本。

【讨论】:

    【解决方案2】:

    如何使用 sys.path[0]

    你可以做类似的事情
    '打印 os.path.join(sys.path[0], sys.argv[0])'

    https://docs.python.org/library/sys.html

    【讨论】:

    • 不太可能实际上是正确的——运行脚本可能不是路径上的第一项。它可能位于 PYTHONPATH 上的任何位置。此外,如果它是用 python -m someModule 启动的,那么 argv[0] 也不相关。
    • @S.Lott - 来自 Pat 链接的文档:“此列表的第一项路径 [0] 是包含用于调用 Python 解释器的脚本的目录。”所以它应该是我想要的,但我决定使用 os.path.abspath(file) :)
    猜你喜欢
    • 2010-11-14
    • 2010-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 2010-10-10
    相关资源
    最近更新 更多