0

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>
Brenduan
  • 9
  • 5
  • 1
    You shouldn't run an import down there in the if clause. Can you share the error message though? – Axblert Dec 22 '19 at 08:05
  • I have added the error, I believe it is because you cannot import a module twice. How would I go about that? – Brenduan Dec 22 '19 at 08:08
  • Python probably understood this is sort of an infinite loop, so it stopped the execution. – Guy Dec 22 '19 at 08:08
  • 1
    This has been discussed before : Imports only happen once. Its called circular circular imports . https://stackoverflow.com/questions/744373/circular-or-cyclic-imports-in-python – Axblert Dec 22 '19 at 08:10
  • in both files put code in function and import at start only once second file to first file and run functions instead of importing. OR better in first function execute second function, and later use `return` to go back to first function. – furas Dec 22 '19 at 10:24

1 Answers1

1

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()
furas
  • 134,197
  • 12
  • 106
  • 148