簡體   English   中英

如何獲取特定 Python 模塊中的變量列表?

[英]How to get a list of variables in specific Python module?

假設我有以下文件結構:

數據文件

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

核心文件

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

我需要獲取 data.py 文件中定義的所有變量。 我怎樣才能做到這一點? 我可以使用dir() ,但它返回模塊的所有屬性,包括__name__等等。

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

通常是這樣做的秘訣,但它引出了一個問題。

為什么?

#!/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

享受,伙計。 :)

這是我為python 3.7編寫的版本(它通過理解中的條件排除了內部dunder方法)

print([v for v in dir(data) 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

我必須制作這些變量的字典。 我使用了這個代碼。

print({item:getattr(my_module, item) for item in dir(my_module) if not item.startswith("__") and not item.endswith("__")})

我提供我的解決方案。 它很方便,因為它允許您顯示來自任何導入模塊的變量。

如果不指定模塊的名稱,則顯示當前模塊的變量列表。

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}")

如果您希望更明確,這是一種迂回的方式:

數據文件

a = [
  foo := [],
  bar := [],
  abc := "def",
]

核心文件

import data

print(data.foo)
print(data.a)

如果您需要變量和分配給它的值,那么

import data

for name ,values in vars(data).items():
    print(name, values)

您可以選擇存儲名稱(腳本中的所有變量名稱)或附加到它的值。

嘗試:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM