Python - 如何在Python shell中以类似grep的方式过滤输出?

3 投票
3 回答
2908 浏览
提问于 2025-04-17 02:07

我在使用Python的命令行界面。为了列出所有的全局变量名,我用的是dir()这个命令,但它会生成一个很长的列表,我想对这个列表进行筛选。我只对那些以'f'开头并且以数字结尾的名字感兴趣。有时候我还只想要用户自己定义的名字,不想要那些以__*__开头和结尾的名字。在Python的命令行里,有没有类似grep的方式来过滤这些输出呢?

3 个回答

2
>>> import re
>>> [item for item in dir() if re.match(r'f.*\d+$',item)]

或者

>>> [item for item in dir() if re.search(r'^f.*\d+$',item)]
2
[name for name in dir() if name.startswith('f') and name[-1].isdigit()]

示例:

>>> f0 = 7
>>> [name for name in dir() if name.startswith('f') and name[-1].isdigit()]
['f0']
1

这段代码是这样的:[n for n in dir() if re.match("f.*[0-9]$", n)]

我把我的PYTHONSTARTUP环境变量设置成指向~/.startup.py这个文件,里面包含了:

# Ned's startup.py file, loaded into interactive python prompts.

print("(.startup.py)")

import datetime, os, pprint, re, sys, time

print("(imported datetime, os, pprint, re, sys, time)")

def dirx(thing, regex):
    return [ n for n in dir(thing) if re.search(regex, n) ]

pp = pprint.pprint

现在我每次打开Python时,都会自动导入一些常用的模块,还能用上我经常在命令行里做的事情的快捷方式。

撰写回答