Reputation: 57
I'm trying to run this code, and all seems to be going well, however, the outputs duplicate and I have no clue why. when I remove the check for "main" (the file I'm working in), it doesn't have the same problem and only returns the output once
def file_exists(name):
try:
exec("import " + name)
return True
except ModuleNotFoundError:
return False
#test
print(file_exists("main")) # -> True (file being worked in)
print(file_exists("module1")) # -> True (module exists in program)
print(file_exists("math")) # -> True
print(file_exists("english")) # -> False
Upvotes: 1
Views: 440
Reputation: 1
OK
1-The problem with running this code too much is that when you import the main
file, it causes the main file to run twice.
2-The second problem is that the module1
function is part of the main
file and must be imported in this way.
from main import module1
Look at this
def module1():
pass
def file_exists(name):
try:
exec(f"import {name}")
return name, True
except:
try:
exec(f"from main import {name}")
return name, True
except Exception:
return name, False
files=["main", "module1", "math", "english"]
for f in files:
print(file_exists(f))
Upvotes: 0
Reputation: 21
Whats happening here is when you include check for "main"
The program runs "import main" in runtime and that actually initialises the main module again
i.e. something like below
def file_exists(name):
try:
exec("import " + name)
return True # return true for initial call,#5. True
except ModuleNotFoundError:
return False
#test
print(file_exists("main")) # -> True (file being worked in), this imports the module and initialises it as its not found in sys.modules
"""
def file_exists(name):
try:
exec("import " + name) - #a duplicate import so executes and moves to next line
return True #returns true
except ModuleNotFoundError:
return False
#test
print(file_exists("main")) #1. True
print(file_exists("module1")) # -> True (module exists in program), 2.True
print(file_exists("math")) # -> True, 3.True
print(file_exists("english")) # 4. False
"""
# after 4th print the control goes back to the check which call the import that will print from (5)
print(file_exists("module1")) # -> True (module exists in program), 6. True
print(file_exists("math")) # -> True, 7.True
print(file_exists("english")) # -> False` 8. True
But if we remove check for main none of the above happens and simply 4 checks with one print statement each are executed, thus only 4 lines of print.
Refer - https://docs.python.org/2/reference/simple_stmts.html#the-import-statement
Upvotes: 0
Reputation: 345
My rough idea is that once main
runs, it runs all import statements, then u run import again using exec
, the subsequent imports fail due to double import of same module name. I would print the exception seen - including type and message.
Upvotes: 1