English 中文(简体)
Python: 确定实际当前模块( 不是 __ main__)
原标题:Python: determine actual current module (not __main__)

我试图确定函数的实际当前模块(如果从别处导入的话),即使当前模块是“顶层脚本环境

这样做听起来可能听起来有点奇怪,但背景是,我需要将一个函数序列化,并解除它(包括参数)在另一台机器上的序列化(包括参数),为此,我需要确保正确的模块,在取消飞行前不会导入到 (否则我就会收到一个错误,说 AttritateError:模块对象没有我的属性_fun )。

到目前为止,我尝试了Insperction :

import inspect
print inspect.getmodule(my_fun)

这使我

<module  __main__  from  example.py >

当然了,我还试图找到一些有用的东西 使用 globals () < () , no luck.

我真正想要的是 。 我想一种黑客化的方法就是用类似的东西从文件名中解析它 。

m_name = __main__.__file__.split("/")[-1].replace(".pyc","")

然后查找模块的名称为 syss.modules[m_name]

是否有更清洁/更好的方法做到这一点?

EDIT: After learning about ipython s "FakeModule" and a bit more googling, I came accross this post, which describes exactly the problem that I m facing, including my current solution to it (which is explicitly importing the current module import current_module and serializing current_module.my_fun instead of my_fun). I m trying to avoid this, as it might not be intuitive for the users of my package.

最佳回答

其实我遇到同样的问题

我用的是:

return os.path.splitext(os.path.basename(__main__.__file__))[0]

和你的"黑客"完全一样 说实话 我觉得这是最好的解决办法

问题回答

我知道这已经过时, 但我在 Python3 找到了一个对我有用的简单解决方案。 长话短说, 还有一个对象 s 'em>spec

import inspect
if obj.__class__.__module__ == "__main__":
    print(inspect.getmodule(obj).__spec__.name)

< 坚固 > 编辑: < / 坚固 > 回想起来, 迄今最好的和最清洁的解决办法是首先避免 < / 最清洁的'处于这种状态; 如果它是正在序列的代码, 则将所有可序列的函数移到由主程序脚本装入的模块中。 这样, 函数的起源就可以在任何任何情况下重新找到, 不需要黑客或特殊案例 。

如果这不可能的话, 我认为您的原解决方案( 从 获取模块名称) 是最好和最简单的。 如果您担心它看起来对您的用户来说是反直觉的, 请用一个好的功能包住它, 并记录它的目的 。

当您以 运行模块时, python 真的不将模块与其正常模块名称连接: 如果您 import example , 它将第二次装入文件, 仿佛它是一个单独的模块。 事实上, 这可能发生在您的情况中, 否则您将无法在 sys.modules 中找到您的模块名称: 模块 example 和模块 和模块 中, 它们是独立的运行时间对象, 您会发现如果您明确更改其中的一个模块变量, 将会发现 。

我不认为任何现有答案能直接回答问题:当模块以 运行时,您如何获得模块的名称?

使用检查大多数步骤...

import inspect

def module_name(obj):
    module_name = obj.__module__

    if "__main__" in module_name:
        # get parent modules of object
        mod_obj = inspect.getmodule(obj) # type: module

        # from the filename of the module, get its name
        mod_suffix  = inspect.getmodulename(inspect.getmodule(obj).__file__)

        # join parent to child with a .
        module_name =  . .join([mod_obj.__package__, mod_suffix])

    return module_name

编辑 : 作为下面的Beanote10 点, 如果您没有做任何与导入路径和模块名称有关的事情, 您可以只做 inspect. getmodule (obj._spec_. name

从Python 3.4开始

importlib.util.find_spec( __main__ ).name




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...