如何在 Python 中获取当前执行文件的路径? [英] How do I get the path of the current executed file in Python?

查看:30
本文介绍了如何在 Python 中获取当前执行文件的路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是一个新手问题,但事实并非如此.一些常见的方法并不适用于所有情况:

This may seem like a newbie question, but it is not. Some common approaches don't work in all cases:

这意味着使用 path = os.path.abspath(os.path.dirname(sys.argv[0])),但是如果您从另一个 Python 脚本运行在另一个目录,这可能会在现实生活中发生.

This means using path = os.path.abspath(os.path.dirname(sys.argv[0])), but this does not work if you are running from another Python script in another directory, and this can happen in real life.

这意味着使用path = os.path.abspath(os.path.dirname(__file__)),但我发现这不起作用:

This means using path = os.path.abspath(os.path.dirname(__file__)), but I found that this doesn't work:

  • py2exe 没有 __file__ 属性,但有 解决方法
  • 当您使用 execute()IDLE 运行时不是 __file__ 属性
  • Mac OS X v10.6 (Snow Leopard) 在那里我得到了 NameError: 全局名称 '__file__' 未定义
  • py2exe doesn't have a __file__ attribute, but there is a workaround
  • When you run from IDLE with execute() there is no __file__ attribute
  • Mac OS X v10.6 (Snow Leopard) where I get NameError: global name '__file__' is not defined

答案不完整的相关问题:

Related questions with incomplete answers:

我正在寻找一种通用解决方案,一种适用于上述所有用例的解决方案.

I'm looking for a generic solution, one that would work in all above use cases.

这是一个测试用例的结果:

Here is the result of a testcase:

a.py: __file__= a.py
a.py: os.getcwd()= C:zzz

b.py: sys.argv[0]= a.py
b.py: __file__= a.py
b.py: os.getcwd()= C:zzz

a.py

#! /usr/bin/env python
import os, sys

print "a.py: sys.argv[0]=", sys.argv[0]
print "a.py: __file__=", __file__
print "a.py: os.getcwd()=", os.getcwd()
print

execfile("subdir/b.py")

文件 subdir/b.py

#! /usr/bin/env python
import os, sys

print "b.py: sys.argv[0]=", sys.argv[0]
print "b.py: __file__=", __file__
print "b.py: os.getcwd()=", os.getcwd()
print

C:.
|   a.py
---subdir
        b.py

推荐答案

您无法直接确定正在执行的主脚本的位置.毕竟,有时脚本根本不是来自文件.例如,它可能来自交互式解释器或仅存储在内存中的动态生成的代码.

You can't directly determine the location of the main script being executed. After all, sometimes the script didn't come from a file at all. For example, it could come from the interactive interpreter or dynamically generated code stored only in memory.

但是,您可以可靠地确定模块的位置,因为模块始终是从文件加载的.如果您使用以下代码创建一个模块并将其与主脚本放在同一目录中,则主脚本可以导入该模块并使用它来定位自身.

However, you can reliably determine the location of a module, since modules are always loaded from a file. If you create a module with the following code and put it in the same directory as your main script, then the main script can import the module and use that to locate itself.

some_path/module_locator.py:

some_path/module_locator.py:

def we_are_frozen():
    # All of the modules are built-in to the interpreter, e.g., by py2exe
    return hasattr(sys, "frozen")

def module_path():
    encoding = sys.getfilesystemencoding()
    if we_are_frozen():
        return os.path.dirname(unicode(sys.executable, encoding))
    return os.path.dirname(unicode(__file__, encoding))

some_path/main.py:

some_path/main.py:

import module_locator
my_path = module_locator.module_path()

如果您在不同目录中有多个主要脚本,则可能需要多个 module_locator 副本.

If you have several main scripts in different directories, you may need more than one copy of module_locator.

当然,如果您的主脚本是由其他一些工具加载的,而这些工具不允许您导入与脚本位于同一位置的模块,那么您就不走运了.在这种情况下,您所追求的信息根本不存在于程序中的任何地方.最好的办法是向该工具的作者提交错误.

Of course, if your main script is loaded by some other tool that doesn't let you import modules that are co-located with your script, then you're out of luck. In cases like that, the information you're after simply doesn't exist anywhere in your program. Your best bet would be to file a bug with the authors of the tool.

这篇关于如何在 Python 中获取当前执行文件的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆