如何获取特定Python模块中的变量列表?

时间:2012-03-18 16:08:24

标签: python

假设我有以下文件结构:

data.py

foo = []
bar = []
abc = "def"

core.py

import data
# do something here #
# a = ...
print a
# ['foo', 'bar', 'abc']

我需要获取data.py文件中定义的所有变量。我怎样才能做到这一点?我可以使用dir(),但它会返回模块的所有属性,包括__name__等等。

6 个答案:

答案 0 :(得分:31)

print [item for item in dir(adfix) if not item.startswith("__")]

通常是这样做的秘诀,但它引出了一个问题。

为什么?

答案 1 :(得分:7)

#!/usr/local/bin/python
# coding: utf-8
__author__ = 'spouk'

def get_book_variable_module_name(module_name):
    module = globals().get(module_name, None)
    book = {}
    if module:
        book = {key: value for key, value in module.__dict__.iteritems() if not (key.startswith('__') or key.startswith('_'))}
    return book

import config

book = get_book_variable_module_name('config')
for key, value in book.iteritems():
    print "{:<30}{:<100}".format(key, value)

示例配置

#!/usr/local/bin/python
# coding: utf-8
__author__ = 'spouk'

import os

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

# database section MYSQL section
DBHOST = 'localhost'
DBNAME = 'simple_domain'
DBPORT = 3306
DBUSER = 'root'
DBPASS = 'root'

# global section
DEBUG = True
HOSTNAME = 'simpledomain.com'
HOST = '0.0.0.0'
PORT = 3000
ADMINS = frozenset(['admin@localhost'])
SECRET_KEY = 'dfg45DFcx4rty'
CSRF_ENABLED = True
CSRF_SESSION_KEY = "simplekey"

结果函数

/usr/local/bin/python2 /home/spouk/develop/python/2015/utils_2015/parse_config_py.py
DBPORT                        3306                                                                                                
os                            <module 'os' from '/usr/local/lib/python2.7/os.pyc'>                                                
DBHOST                        localhost                                                                                           
HOSTNAME                      simpledomain.com                                                                                    
HOST                          0.0.0.0                                                                                             
DBPASS                        root                                                                                                
PORT                          3000                                                                                                
ADMINS                        frozenset(['admin@localhost'])                                                                      
CSRF_SESSION_KEY              simplekey                                                                                           
DEBUG                         1                                                                                                   
DBUSER                        root                                                                                                
SECRET_KEY                    dfg45DFcx4rty                                                                                       
CSRF_ENABLED                  1                                                                                                   
DBNAME                        simple_domain                                                                                       

Process finished with exit code 0

享受,伙计。 :)

答案 2 :(得分:1)

我提供我的解决方案。方便的是,它允许您显示来自任何导入模块的变量。

如果不指定模块名称,则显示当前模块的变量列表。

import sys

def print_settings(module_name=None):
    module_name = sys.modules[__name__] if not module_name else module_name
    variables = [
        (key, value)
        for (key, value) in vars(module_name).items()
        if (type(value) == str or type(value) == int or type(value) == float)
        and not key.startswith("_")
    ]

    for (key, value) in variables:
        print(f"{key: <20}  {value}")

答案 3 :(得分:0)

尝试:

for vars in dir():
 if vars.startswith("var"):
   print vars

答案 4 :(得分:0)

这是我为python 3.7编写的版本(它通过理解条件排除了内部dunder方法)

print([v for v in dir() if v[*2] != "__"])

下面是一个更长但完整的工作示例,

"""an example of a config file whose variables may be accessed externally"""
# Module variables
server_address = "172.217.167.68"
server_port = 8010
server_to_client_port = 8020
client_to_server_port = 8030
client_buffer_length = 4096
server_buffer_length = 2048

def printVariables(variable_names):
    """Renders variables and their values on the terminal."""
    max_name_len = max([len(k) for k in variable_names])
    max_val_len = max([len(str(globals()[k])) for k in variable_names])

    for k in variable_names:
        print(f'  {k:<{max_name_len}}:  {globals()[k]:>{max_val_len}}')

if __name__ == "__main__":
    print(__doc__)
    ks = [k for k in dir() if (k[:2] != "__" and not callable(globals()[k]))]
    printVariables(ks)

上面的代码输出:

an example of a config file whose variables may be accessed externally
  client_buffer_length :            4096
  client_to_server_port:            8030
  server_address       :  172.217.167.68
  server_buffer_length :            2048
  server_port          :            8010
  server_to_client_port:            8020

答案 5 :(得分:0)

我必须对这些变量做一个字典。我使用了这段代码。

df = pd.read_excel("Workbook1.xlsx", converters={'ID':str})
df = df.drop("Unnamed: 0", axis=1) #drop this column since it is not useful