Calling a script requiring user input from another script

M

mzagursk

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.
 
C

Chris Rebert

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,141
Latest member
BlissKeto
Top