簡體   English   中英

如何獲取python源文件的功能實例列表?

[英]How do I get a list of function instances for a python source file?

假設我有一個名為example.py的文件,其內容如下:

def func_one(a):
    return 1

def func_two(b):
    return 2

def func_three(b):
    return 3

我如何獲得該文件的功能實例列表? 我嘗試過使用compilerparserast模塊,但是我真的無法弄清楚。 可能比這容易得多,但是這超出了我的理解范圍。

編輯:明確地說,我不想導入函數。

您可以使用檢查模塊:

>>> import inspect
>>> import example
>>> inspect.getmembers(example, inspect.isroutine)
[('func_one', <function func_one at 0x0238CBB0>), ('func_three', <functi
three at 0x0240ADB0>), ('func_two', <function func_two at 0x0240ADF0>)]

您可以使用dir 這將返回當前本地范圍內的名稱列表。 盡管這可能返回的不僅僅是函數名。

>>> import utils
>>> utils.__name__
'utils'
>>> dir(utils)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'human_number', 'islice', 'math', 'prime_factors', 'primes_sieve', 'primes_sieve1', 'proper_divisors', 'pyth_triplet', 'square_of_sum', 'sum_of_nums', 'sum_of_squares', 'test', 'triangle_nums', 'window']

如果您真的不想像這樣導入名稱空間:

import examples
print dir(examples)

['__builtins__', '__doc__', '__file__', '__name__', 
'__package__', 'func_one', 'func_three', 'func_two'] #OUTPUT

您可以openread文件,搜索所有def並將其附加到列表中,從而返回所有函數和方法定義名稱。

您可以使用globals()函數,它會在所有可以找到函數的全局環境中返回一個字典。 例:

d = globals().copy()
l = []
[l.append(k) for k in d if k.startswith('func')]

暫無
暫無

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

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