1
#checkapi.py
import time

def add(a,b):
    return a + b
def loop():
    while True:
        time.sleep(10)
        print("loop running")
loop()
#apicheck.py
import checkapi

print(checkapi.add(5, 6))
output
------
apicheck.py showing "loop running"

please check out this. Why this happening.

Q. How to call a running method and get it's return value ?.

3
  • 2
    You can't "call a running method". Calling a method by definition runs it. What are you trying to actually accomplish here? What do you want to do? Commented Nov 21, 2021 at 1:40
  • I don't understand the question. When you import checkapi, the loop function starts running, because it says loop() at the end of that file. Because that function has an infinite loop, nothing else can happen afterward. It's not at all clear what you want to happen instead. Commented Nov 21, 2021 at 1:49
  • 1
    You should guard against the file being run as a script vs loaded as a module. Do if __name__ == "__main__": loop() to guard against this. Commented Nov 21, 2021 at 1:55

1 Answer 1

1

Modify checkapi.py in following way:

#checkapi.py
import time

def add(a,b):
    return a + b
def loop():
    while True:
        time.sleep(10)
        print("loop running")

if __name__ == '__main__':
    loop()

this will solve your issue. if __name__ == '__main__' says Python to run loop() function only if you execute script itself like python checkapi.py, but if you import it from other module through import checkapi then loop() is not executed and you can use this module without trouble.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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