Python Forum
grep in python interpreter
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
grep in python interpreter
#7
(Jul-08-2017, 01:44 PM)rahul1913 Wrote: >>> dir(os) | grep system

Interesting idea. I had this idea over and over with generators. Piping generators together like shell commands in a shell.

The funny thing is, that you can make it possible in Python.
This example includes: custom Exception, raising exceptions, defining behavior with __ror__, using a dict like a switch statement, generator, context manager
import types


class GrepError(Exception):
   pass


class Grep:
    def __init__(self, search_string):
        self.search_string = search_string
   
    def __ror__(self, other):
        action = {
            types.ModuleType: dir,
            list: iter,
            tuple: iter,
            dict: iter,
            set: iter,
            str: self.__file,
            }
        function = action.get(type(other))
        if function is None:
            raise GrepError('{} is not supported'.format(type(other)))
        iterable = function(other)
        for entry in iterable:
            if self.search_string in entry:
                yield entry

    def __file(self, path):
        with open(path) as fd:
            for line in fd:
                yield line
A stripped down solution which supports only ModuleType and without error checking, just for better understanding what happens.
class Grep:
    def __init__(self, search_string):
        self.search_string = search_string
  
    def __ror__(self, other):
        for entry in dir(other):
            if self.search_string in entry:
                yield entry
list('/var/log/pacman.log' | grep('error'))
import os
list(os | grep('spa'))
Output:
['_fspath', '_spawnvef', 'fspath', 'spawnl', 'spawnle', 'spawnlp', 'spawnlpe', 'spawnv', 'spawnve', 'spawnvp', 'spawnvpe']
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
grep in python interpreter - by rahul1913 - Jul-08-2017, 01:44 PM
RE: grep in python interpreter - by ichabod801 - Jul-08-2017, 01:57 PM
RE: grep in python interpreter - by rahul1913 - Jul-08-2017, 02:08 PM
RE: grep in python interpreter - by ichabod801 - Jul-08-2017, 02:11 PM
RE: grep in python interpreter - by snippsat - Jul-08-2017, 03:26 PM
RE: grep in python interpreter - by Larz60+ - Jul-08-2017, 04:46 PM
RE: grep in python interpreter - by DeaD_EyE - Jul-08-2017, 05:55 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020