Calling a script requiring user input from another script

Chris Rebert clp2 at rebertia.com
Wed Feb 18 10:18:33 CET 2009


On Wed, Feb 18, 2009 at 1:00 AM, mzagursk at gmail.com <mzagursk at gmail.com> wrote:
> I'm kind of new to this so bear with me.
>
> I have a script made that requires user input (lets call it script A)
> while it's running.  However, I would like to create another script
> (script B) that can batch process (i.e. run script A over and over
> with different user inputs based on script B).  Is this possible?  and
> how so?  Thanks in advance.

Define a function in A that lets its functionality be used
programmatically. Then use the `if __name__ == "__main__"` trick to
have A take input from the user and call the function you just defined
 with the user input if it's run as a script.

In B, import A's function and call it repeatedly on the inputs.

Example (assume addition is A's fancy functionality):

#A.py BEFORE:
while True:
    input_ = raw_input()
    if input_ == "exit":
        break
    x = int(input_)
    y = int(raw_input())
    print x + y

#A.py AFTER:
#functionality refactored into a function
def add(x, y):
    return x + y

if __name__ == "__main__":
    while True:
        if input_ == "exit":
            break
        x = int(input_)
        y = int(raw_input())
        print add(x, y)#use the function

#B.py
from A import add

for i,j in some_input_pairs:
    add(i, j)#use the function


Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list