0

Ok first bit of a background.

So.. right now, I have a code say( loop.py) which is nothing but a big for loop... which takes in input for stdin and do some manipulation to that string and then i write the output.

so something like

#loop.py
from clean import *
for line in sys.stdin:
     clean_line = clean(line)
     print clean_line

And I run this as

cat input.txt | python loop.py

So, clean.py is certain cleaning logic which user writes.

Now, here we have a "clean" function.. for some it is certain extraction logic..

so you may have

#loop.py
from clean import *
for line in sys.stdin:
     extract_line = extract(line)
     print extract_line

Now, this loop.py hasnt changed.. and it will not change..

So.. maybe i can spell out the experience and someone can help me figure out how to implement that..

What I want is user to write those custom functions..So user writes...

my_custom_func.py

import run_loop
def my_own_logic(string):
    # my logic goes in here

run_loop.run(my_own_logic)

and what this does is automatically execute the loop.py and this my_own_logic function is pushed in that loop?

I hope I am making any sense... Am i?

4 Answers 4

2

This is fairly straightforward:

def run(func):
    for line in sys.stdin:
        print func(line)
Sign up to request clarification or add additional context in comments.

Comments

1

Python have first-class functions, meaning they can be passed around to other functions without problems.

Example:

def foo(s):
    print(s)

def bar(f, s):
    f(s)

bar(foo, 'Hello world')

Comments

1

run_loop.py

import sys

def run(func):
    for line in sys.stdin:
        processed = func(line)
        print processed

Treat functions as any other objects (int, str, list, ...).

Comments

1

Rule of thumb: say you have a function like

def f(x): return x+1

Then f refers to the function itself while f() (followed by parenthesis) to the evaluation of the function.

>>> print f
<function f at 0x0000000001FD9DD8>
>>> print f(1)
2

So, if you want to process a list with an arbitrary function, you have a few ways to do it:

def f(x): return x+1
def g(x): return x*2

>>> def procList(fun,l):
...     for x in l:
...         print fun(x)
...
>>> l=[1,2,3]
>>> procList(f,l)
2
3
4
>>> procList(g,l)
2
4
6
>>>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.