import re
pattern = re.compile("def (.*)\(")
for i, line in enumerate(open('Example.py')):
for match in re.finditer(pattern, line):
print '%s: %s' % (i+1, match.groups()[0])
import ast
import sys
def top_level_functions(body):
return (f for f in body if isinstance(f, ast.FunctionDef))
def parse_ast(filename):
with open(filename, "rt") as file:
return ast.parse(file.read(), filename=filename)
if __name__ == "__main__":
for filename in sys.argv[1:]:
print(filename)
tree = parse_ast(filename)
for func in top_level_functions(tree.body):
print(" %s" % func.name)
除了前面的回答中提到的dir(module)或者help(module),也可以尝试:
—打开ipython
- import module_name .使用实例
- type module_name,按tab键。它会打开一个小窗口,列出python模块中的所有函数。< br >
看起来很整洁。< br > < / p >
下面是hashlib模块的所有函数的代码片段
(C:\Program Files\Anaconda2) C:\Users\lenovo>ipython
Python 2.7.12 |Anaconda 4.2.0 (64-bit)| (default, Jun 29 2016, 11:07:13) [MSC v.1500 64 bit (AMD64)]
Type "copyright", "credits" or "license" for more information.
IPython 5.1.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: import hashlib
In [2]: hashlib.
hashlib.algorithms hashlib.new hashlib.sha256
hashlib.algorithms_available hashlib.pbkdf2_hmac hashlib.sha384
hashlib.algorithms_guaranteed hashlib.sha1 hashlib.sha512
hashlib.md5 hashlib.sha224
r = globals()
sep = '\n'+100*'*'+'\n' # To make it clean to read.
for k in list(r.keys()):
try:
if str(type(r[k])).count('function'):
print(sep+k + ' : \n' + str(r[k].__doc__))
except Exception as e:
print(e)
输出:
******************************************************************************************
GetNumberOfWordsInTextFile :
Calcule et retourne le nombre de mots d'un fichier texte
:param path_: le chemin du fichier à analyser
:return: le nombre de mots du fichier
******************************************************************************************
write_in :
Ecrit les donnees (2nd arg) dans un fichier txt (path en 1st arg) en mode a,
:param path_: le path du fichier texte
:param data_: la liste des données à écrire ou un bloc texte directement
:return: None
******************************************************************************************
write_in_as_w :
Ecrit les donnees (2nd arg) dans un fichier txt (path en 1st arg) en mode w,
:param path_: le path du fichier texte
:param data_: la liste des données à écrire ou un bloc texte directement
:return: None
# Get this script's name.
import os
script_name = os.path.basename(__file__).rstrip(".py")
# Import it from its path so that you can use it as a Python object.
import importlib.util
spec = importlib.util.spec_from_file_location(script_name, __file__)
x = importlib.util.module_from_spec(spec)
spec.loader.exec_module(x)
# List the functions defined in it.
from inspect import getmembers, isfunction
list_of_functions = getmembers(x, isfunction)
def _inspect_tasks():
import inspect
return { f[0].replace('task_', ''): f[1]
for f in inspect.getmembers(sys.modules['__main__'], inspect.isfunction)
if f[0].startswith('task_')
}
示例输出:
{
'install': <function task_install at 0x105695940>,
'dev': <function task_dev at 0x105695b80>,
'test': <function task_test at 0x105695af0>
}
完整版
我希望用方法的名称来定义CLI任务名称,而不必重复。
# EYZ0
#!/usr/bin/env python3
import sys
from subprocess import run
def _inspect_tasks():
import inspect
return { f[0].replace('task_', ''): f[1]
for f in inspect.getmembers(sys.modules['__main__'], inspect.isfunction)
if f[0].startswith('task_')
}
def _cmd(command, args):
return run(command.split(" ") + args)
def task_install(args):
return _cmd("python3 -m pip install -r requirements.txt -r requirements-dev.txt --upgrade", args)
def task_test(args):
return _cmd("python3 -m pytest", args)
def task_dev(args):
return _cmd("uvicorn api.v1:app", args)
if __name__ == "__main__":
tasks = _inspect_tasks()
if len(sys.argv) >= 2 and sys.argv[1] in tasks.keys():
tasks[sys.argv[1]](sys.argv[2:])
else:
print(f"Must provide a task from the following: {list(tasks.keys())}")
示例无参数:
λ ./tasks.py
Must provide a task from the following: ['install', 'dev', 'test']
使用额外参数运行test的示例:
λ ./tasks.py test -qq
s.ssss.sF..Fs.sssFsss..ssssFssFs....s.s