saturns
saturns

Reputation: 57

using exec() to parse an import statement

How do I use this format of code to find if a module exists within a python program? I need to specifically use exec() to parse an import statement.

def file_exists(name):
  try:
    exec()
  return True #if the file does exist
  except:
    return False

#tests
file_exists(module1) #should return true because there is a module named module1
file_exists(module2) #should return false because there is not a module named module2.

Upvotes: 0

Views: 65

Answers (1)

martineau
martineau

Reputation: 123473

It's unclear why you specifically must use exec() because it's a poor way of doing it — unless this is homework or something — but here's how it could be done:

def file_exists(name):
    try:
        exec(f'import {name}')
    except ModuleNotFoundError:
        return False
    else:
        return True

# tests
print(file_exists('sys'))      # -> True 
print(file_exists('module2'))  # -> False

Upvotes: 1

Related Questions