On 11/28/2016 08:08 AM, Ganesh Pal wrote: > I was trying to write a function that will return me the unique number > associated with each employee id.The command has the output in the below > pattern > > Linux-Box-1# employee_details ls > List of names: > 100910bd9 s7018 > 100d60003 s7019 > 110610bd3 s7020 > 100d60002 s7021 > > > Linux-Box-1# employee_details ls | grep "s7020" | awk '{print $1}' > 100d60003 > > It's a one liner in Shell :) > > > I tried converting the same in the python style , Any better suggestion > and loop holes in the below program
Well Bash is really good at some things. Piping commands together is one of those things. Python can do such things but not in as compact a way. For one Python has no quick way of interfacing with subprograms as if they were language-level constructs like Bash does. But it still can do a lot of the same tasks that shell scripting does. Read on. In many respects, generators are the Python equivalent of pipes. See this: http://www.dabeaz.com/generators/, specifically http://www.dabeaz.com/generators/Generators.pdf Here's a simple grep-like filter that searches lines: def simple_grep(search_in, look_for): for line in search_in: if look_for in line: yield line import sys for result in simple_grep(sys.stdin, "s2070"): print result.split()[0] This obviously does not run a subprogram, but could feed the filter input from any file-like object that returns lines. The beauty of generators is that you can string them together just like you would do in Bash with pipes. And they can potentially be fairly fast, especially if you can reduce the number of lines the generators have to process by putting the faster filters earlier on in the chain (much like you would optimize a database query by pushing selections ahead of joins). Though this is not shorter than your code, nor is it substantially different, it does have the advantage that the simple_grep() generator can be used in multiple places and could even be placed in utility library. -- https://mail.python.org/mailman/listinfo/python-list