简体   繁体   中英

Python - how to filter an output in a python shell in a grep-like way?

I work in a Python shell. In order to produce a list of all global names I use dir (), but it generates a very long list, which I would like to filter. I am interested only in the names which begin with 'f' and end with digits. Sometimes I also need only user-defined names, no __*__ names. Is there any grep-like method in a Python shell to filter its output?

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

Example:

>>> f0 = 7
>>> [name for name in dir() if name.startswith('f') and name[-1].isdigit()]
['f0']
>>> import re
>>> [item for item in dir() if re.match(r'f.*\d+$',item)]

or

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

[n for n in dir() if re.match("f.*[0-9]$", n)]

I set my PYTHONSTARTUP environment variable to point to ~/.startup.py which contains:

# 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

Now I always have a few handy modules imported, and I have shortcuts available for things I often do in the shell.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM