【发布时间】:2017-05-24 02:52:06
【问题描述】:
我包含一个 python 文件 commands.py 使用 导入命令
文件如下:
import datetime
def what_time_is_it():
today = datetime.date.today()
return(str(today))
def list_commands():
all_commands = ('list_commands', 'what time is it')
return(all_commands)
我希望主脚本列出 commands.py 中的函数,所以我使用了dir(commands),它给出了输出:
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'datetime', 'list_commands', 'what_time_is_it']
然后我尝试使用正则表达式删除包含'__'的项目,如下所示:
commands_list = dir(commands)
for com in commands_list:
if re.match('__.+__', com):
commands_list.remove(com)
else:
pass
这不起作用。如果我尝试在没有 for 循环或正则表达式的情况下执行此操作,它会声称该条目(我刚刚从 print(list) 复制并粘贴的条目不在列表中。
作为第二个问题,我可以让 dir 只列出函数,而不是“日期时间”吗?
【问题讨论】:
-
不需要
regex我不认为。new_lst = [item for item in lst if '__' not in item] -
我会在这里使用列表理解。
[i for i in dir(commands) if not (i.startswith('__') and i.endswith('__'))]