本文介绍了在__main__.py中使用模块自己的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从__main__.py内部访问模块的数据.

I’m trying to access a module’s data from inside its __main__.py.

结构如下:

mymod/
    __init__.py
    __main__.py

现在,如果我在__init__.py中公开这样的变量:

Now, if I expose a variable in __init__.py like this:

__all__ = ['foo']
foo = {'bar': 'baz'}

如何从__main__.py访问foo?

推荐答案

您需要将软件包包含在sys.path中,将包含mymod的目录添加到__main__.py中的sys.path,或使用-m开关.

You need to either have the package already in sys.path, add the directory containing mymod to sys.path in __main__.py, or use the -m switch.

要将mymod添加到路径中,看起来像这样(在__main__.py中):

To add mymod to the path would look something like this (in __main__.py):

import sys
import os
path = os.path.dirname(sys.modules[__name__].__file__)
path = os.path.join(path, '..')
sys.path.insert(0, path)
from myprog import function_you_referenced_from_init_file

使用-m开关将会:

python -m mymod

有关更多讨论,请参见此答案.

See this answer for more discussion.

这篇关于在__main__.py中使用模块自己的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 08:00
查看更多