简体   繁体   English

Python-通过回溯获取调用模块的路径,有问题吗?

[英]Python - Getting calling module's path via traceback, problems?

In python, I often find myself loading package resources through calls such as the following: 在python中,我经常发现自己通过诸如以下的调用来加载软件包资源:

import os
fp = open(os.path.join(os.path.dirname(os.path.realpath(__file__)),
                       "resource.json"), "r")

I've been considering using a library function such as the following to eliminate this ugliness. 我一直在考虑使用类似以下的库函数来消除这种难看。 The issue is that the function would live in a library, not the file that I want to get the directory of. 问题在于该函数将存在于库中,而不是我要获取其目录的文件中。 I can get around this with the traceback package, such as with the following: 我可以使用traceback包解决此问题,例如以下内容:

import os, traceback
def with_module_directory(filename):
    return os.path.join(os.path.dirname(traceback.extract_stack()[-2][0]),
                        filename)

Now if with_module_directory() lives in /home/user1/mylibs/utils.py , when a module in /home/user1/myscripts makes the call with_module_directory("resource.json") , the result will be "/home/user1/myscripts/resource.json" , as desired. 现在,如果with_module_directory()位于/home/user1/mylibs/utils.py ,则当/home/user1/myscripts的模块调用with_module_directory("resource.json") ,结果将为"/home/user1/myscripts/resource.json" ,根据需要。

I'm worried however that doing this is in some way dangerous. 但是,我担心这样做在某种程度上很危险。 Manually looking at the stack trace feels like a generally bad thing, like I'm breaking encapsulation. 手动查看堆栈跟踪感觉像是一件坏事,就像我要破坏封装一样。 But I can't think of any concrete issues, so I pose the question: Can anyone think of a problem that could be created by doing this? 但是我无法想到任何具体的问题,所以我提出了一个问题:任何人都可以想到这样做可能产生的问题吗? Is it bad practice for any specific reason? 是出于某种特定原因的不良做法吗?

Note: I realize I could just force the user to make a call like with_module_path("resource.json", __file__) , but if there's no actual reason to avoid the simpler interface then I'd prefer to use it. 注意:我意识到我可以强迫用户进行with_module_path("resource.json", __file__)类的调用,但是如果没有真正的理由避免使用更简单的界面,那么我更愿意使用它。

To find the location of a module, function, or class, use the inspect module: 要查找模块,函数或类的位置,请使用inspect模块:

import inspect
print(inspect.getsourcefile(some_module))

You can use this to find the location of the code units you are interested in. If you put this in a library, just wrap it in a function that takes an argument. 您可以使用它来查找您感兴趣的代码单元的位置。如果将其放在库中,只需将其包装在带有参数的函数中即可。

Actually you could do the same with __file__ , if necessary: Just pass it as the argument to a function that will do the rest. 实际上,如果需要,您可以使用__file__进行相同的操作:只需将其作为参数传递给将完成其余工作的函数。

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

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