Jul-08-2017, 05:55 PM
(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 lineA 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!
All humans together. We don't need politicians!