当CWD发生变化时,如何在Python模块中使用相对路径?

时间:2021-01-07 07:12:55

I have a Python module which uses some resources in a subdirectory of the module directory. After searching around on stack overflow and finding related answers, I managed to direct the module to the resources by using something like

我有一个Python模块,它使用模块目录的子目录中的一些资源。在搜索堆栈溢出并找到相关答案后,我设法通过使用类似的东西将模块引导到资源

import os
os.path.join(os.path.dirname(__file__), 'fonts/myfont.ttf')

This works fine when I call the module from elsewhere, but it breaks when I call the module after changing the current working directory. The problem is that the contents of __file__ are a relative path, which doesn't take into account the fact that I changed the directory:

当我从其他地方调用模块时这很好用,但是在我更改当前工作目录后调用模块时它会中断。问题是__file__的内容是一个相对路径,它没有考虑到我更改目录的事实:

>>> mymodule.__file__
'mymodule/__init__.pyc'
>>> os.chdir('..')
>>> mymodule.__file__
'mymodule/__init__.pyc'

How can I encode the absolute path in __file__, or barring that, how can I access my resources in the module no matter what the current working directory is? Thanks!

如何编码__file__中的绝对路径,或者禁止这样做,无论当前工作目录是什么,我如何访问模块中的资源?谢谢!

1 个解决方案

#1


42  

Store the absolute path to the module directory at the very beginning of the module:

将模块目录的绝对路径存储在模块的最开头:

package_directory = os.path.dirname(os.path.abspath(__file__))

Afterwards, load your resources based on this package_directory:

然后,根据此package_directory加载资源:

font_file = os.path.join(package_directory, 'fonts', 'myfont.ttf')

And after all, do not modify of process-wide resources like the current working directory. There is never a real need to change the working directory in a well-written program, consequently avoid os.chdir().

毕竟,不要修改当前工作目录等流程范围的资源。从来没有真正需要在编写良好的程序中更改工作目录,因此避免使用os.chdir()。

#1


42  

Store the absolute path to the module directory at the very beginning of the module:

将模块目录的绝对路径存储在模块的最开头:

package_directory = os.path.dirname(os.path.abspath(__file__))

Afterwards, load your resources based on this package_directory:

然后,根据此package_directory加载资源:

font_file = os.path.join(package_directory, 'fonts', 'myfont.ttf')

And after all, do not modify of process-wide resources like the current working directory. There is never a real need to change the working directory in a well-written program, consequently avoid os.chdir().

毕竟,不要修改当前工作目录等流程范围的资源。从来没有真正需要在编写良好的程序中更改工作目录,因此避免使用os.chdir()。