Home > OS >  Calling another file and generating output in Python
Calling another file and generating output in Python

Time:06-08

I have two files named A and B. I want to call B in A and get the output for each t defined in A. The desired output is attached.

File A:

import numpy as np
t = np.linspace(0,1,10)
print([t])
x = -t
print("x =",[x])

File B:

def B(x):
    B=x**2
    print(B)

The desired output is

t = [array([0.        , 0.11111111, 0.22222222, 0.33333333, 0.44444444,
       0.55555556, 0.66666667, 0.77777778, 0.88888889, 1.        ])]
x = [array([-0.        , -0.11111111, -0.22222222, -0.33333333, -0.44444444,
       -0.55555556, -0.66666667, -0.77777778, -0.88888889, -1.        ])]
A = [array([0.        , 0.01234568, 0.04938272, 0.11111111, 0.19753086,
       0.30864198, 0.44444444, 0.60493827, 0.79012346, 1.        ])]

CodePudding user response:

Adding the following lines in B.py:

from B import B
B(x)

# [0. 0.01234568 0.04938272 0.11111111 0.19753086 0.30864198 0.44444444 0.60493827 0.79012346 1.]

will get your result. It will print the result and not return them. If you need to use the output of B function, you must return it instead of printing. So, B.py must be changed to:

def B(x):
    B = x ** 2
    return B

and call it from A as:

output = B(x)

# print("A =", output)  # or print(B(x))   # If you want to see the results
# A = [0. 0.01234568 0.04938272 0.11111111 0.19753086 0.30864198 0.44444444 0.60493827 0.79012346 1.]

CodePudding user response:

  1. Define a function in B that does what you want
  2. Import this function in A
  3. Call on each relevant value of t
  • Related