简体   繁体   English

给定文件名获取其绝对路径

[英]Given a filename get its absolute path

I am developing a python library and the end-user who uses my library in their respective application should be able to provide a configuration file in the root path of their application which my library will read in run-time. 我正在开发一个python库,在各自应用程序中使用我的库的最终用户应该能够在其应用程序的根路径中提供一个配置文件,我的库将在运行时读取该配置文件。 The end-user's application can be any Project like a Simple Python Project, Django, Flask etc 最终用户的应用程序可以是任何项目,例如简单Python项目,Django,Flask等

In my library, I'm planning to have the following code. 我打算在我的图书馆中包含以下代码。 The following is a piece of code that will be exported as a library. 以下是一段将作为库导出的代码。 for example, my-library 例如我的图书馆

def read_config():
   BASE_DIR = # Some code
   with open(os.path.join(BASE_DIR, 'test.conf')) as f:
      f.read()

I'm not sure how to get the value of BASE_DIR of the end-user's application through my library 我不确定如何通过我的库获取最终用户应用程序的BASE_DIR值

I have seen some posts related to getting root path using settings.py which resides in the root path of the application. 我已经看到了一些与使用settings.py获取根路径有关的帖子,该文件位于应用程序的根路径中。 But in my case since I have no idea about end user's project structure, I guess I cannot use this. 但是就我而言,由于我对最终用户的项目结构一无所知,我想我不能使用它。

Note -The enduser would install my library as a package using pip install my-library 注意 -最终用户可以使用pip install my-library将我的库作为软件包安装

I think you may want to rethink your approach. 我认为您可能需要重新考虑您的方法。

I don't think its going to be possible to dynamically retrieve a base directory easily, but then you may not have to. 我认为不可能轻松地动态检索基本目录,但是您可能不必这样做。 Instead of relying on a settings file, make your app have its own settings static class that you can retrieve any configurations you need. 不必依赖设置文件,而是使您的应用程序具有自己的设置静态类,您可以检索所需的任何配置。 If an end user wishes to customize any settings then they can either introduce or expand an initialization step to their application. 如果最终用户希望自定义任何设置,则他们可以在其应用程序中引入或扩展初始化步骤。

This is the same way that django does it, django uses its own settings class which end users can override and set their own values for. 这与django的方法相同,django使用其自己的设置类,最终用户可以覆盖并为其设置自己的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM