2014-03-28 69 views
0

我想要做这样的事情的所有方法:遍历Python程序

def a(): 
    # do stuff 
    return stuff 

def b(): 
    # do stuff 
    return different_stuff 

def c(): 
    # do one last thing 
    return 200 

for func in this_file: 
    print func_name 
    print func_return_value 

我基本上是想模仿这种瓶的应用程序,而无需将烧瓶部分:

app = Flask(__name__) 
app.register_blueprint(my_bp, url_prefix='/test') 
my_bp.data = fake_data 

def tests(): 
    with app.test_client() as c: 
    for rule in app.url_map.iter_rules(): 
     if len(rule.arguments) == 0 and 'GET' in rule.methods: 
     resp = c.get(rule.rule) 
     log.debug(resp) 
     log.debug(resp.data) 

这是可能的?

回答

3

像这样:

import sys 

# some functions... 
def a(): 
    return 'a' 

def b(): 
    return 'b' 

def c(): 
    return 'c' 

# get the module object for this file  
module = sys.modules[__name__] 

# get a list of the names that are in this module 
for name in dir(module): 
    # get the Python object from this module with the given name 
    obj = getattr(module, name) 
    # ...and if it's callable (a function), call it. 
    if callable(obj): 
     print obj() 

运行这给:

[email protected] ~/temp:python moduleTest.py 
a 
b 
c 

注意,功能不一定会在定义的顺序,因为他们被称为在这里。

1

可能:

def a(): return 1 
def b(): return 2 
def c(): return 3 

for f in globals().values(): 
    if callable (f): continue 
    print f.__name__ 
    print f() 
+1

使用'callable(f)'来确定是否可以调用'f'。比照http://docs.python.org/2.7/library/functions.html#callable – bgporter

+1

@bgporter谢谢。编辑 – Hyperboreus

1

使用此代码来创建Python模块get_module_attrs.py

import sys 
module = __import__(sys.argv[1]) 
for name in dir(module): 
    obj = getattr(module, name) 
    if callable(obj): 
     print obj.__name__ 

然后,你可以把它作为$python get_module_attrs.py <name_of_module>

享受它!