Brenduan
Brenduan

Reputation: 13

Py file import stops importing

when I try to run these two scripts together after a few tries it stops working? Is this because of the import module?

test1.py

test = input("Go to new script?: ")
if test=="yes":
    print("going to new script")
    import test2

test2.py

test = input("Go to old script?: ")
if test=="yes":
    print("going to new script")
    import test1

Error is that it ends itself.

C:\Users\bj\Desktop>python test1.py
Go to new script?: yes
going to new script
Go to old script?: yes
going to new script
Go to new script?: yes
going to new script

C:\Users\bj\Desktop>

Upvotes: 0

Views: 183

Answers (1)

furas
furas

Reputation: 142641

import remember already imported files and it doesn't import them again.

Better put code in functions and import function from second file to first file and run it in loop . Second function should use return to go back to first function.

test2.py

def func2():
    while True:
        answer = input("Go to old script?: ")
        if answer.lower() == "y":
            print("Going back to old script")
            return

test1.py

from test2 import func2

def func1():
    while True:
        answer = input("Go to new script?: ")
        if answer.lower() == "y":
            print("Going to new script")
            func2()

func1()

Upvotes: 1

Related Questions