CoderMJ
CoderMJ

Reputation: 17

Have to pass input from first python file to second python file and second python file function should be called inside first python file

There are two python files namely script_a.py and script_b.py I have to pass input from script_a.py to script_b.py function and that script_b.py function should be called inside script_a.py

script_a.py

from script_b import maximum
input1=5
input2=6
def script_a(input1,input2):
    input1,input2=input2,input1
    return input1,input2
print(script_a(input1,input2))
maximum(input1,input2)

script_b.py

import script_a

def maximum(a, b):
    if a >= b:
        return a
    else:
        return b
a = script_a.input1
b = script_a.input2
print(maximum)

when I execute script_a.py I have to get answer for maximum function also

Upvotes: 0

Views: 50

Answers (2)

Jason Dominguez
Jason Dominguez

Reputation: 264

A quick solution to stop seeing the answer for the maximum function when running script_a.py would be to remove the last line of script_a.py - maximum(input1, input2).

However, you should try to make your scripts as isolated as possible when using them for function or class definitions, in order to allow for efficient reuse. script_a.py and script_b.py should just provide function definitions. You could then have a main.py file which you will actually run. This will import then necessary function from the scripts and use them. For example:

script_a.py

def script_a(input1,input2):
    input1,input2=input2,input1
    return input1,input2

script_b.py

def maximum(a, b):
    if a >= b:
        return a
    else:
        return b

main.py

from script_a import script_a
from script_b import maximum

def run_script_a(input1, input2):
    print(script_a(input1, input2))

def run_script_b(input1, input2):
    print(script_b(input1, input2))

def main():
    input1 = 5
    input2 = 6

    run_script_a(input1, input2)
    #run_script_b(input1, input2)

if __name__ == "__main__":
    main()
    

You can uncomment the script that you want to run in the main function. This example is a bit verbose for such a simple program but if more efficient for code reuse in larger projects.

Upvotes: 1

yokus
yokus

Reputation: 173

When you write def maximum(a, b) in script_b file you are not using the imported script_a.input1 and script_a.input2. You are just declaring a function with parameters named a and b.

When you call maximum function from anywhere it does not care about a and b variables declared outside and above of function definition. They are out of scope.

Upvotes: 0

Related Questions