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

查看:436
本文介绍了如何在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__属性
  • 我得到NameError: global name '__file__' is not defined
  • 的OS X 10.6
  • py2exe doesn't have a __file__ attribute, but there is a workaround
  • When you run from IDLE with execute() there is no __file__ attribute
  • OS X 10.6 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天全站免登陆