Search code examples
pythonpython-3.xfunctionmodule

Python string instead of unknown module name


I have made a simple code to something like this:

  • It accepts a string (name) from user
  • then it do some customization to the string (turn lowercase and replacing space with "_"{under score})
  • then after customization, it will search for a file with same name as string
  • then display the content of file. here is its code:
    import coder
    import time
    import calc
    
    mainfunc = ["clears", "action mode"]
    
    main_loop = "main"
    coder.clear_screen()
    while main_loop == "main":
        ask = input("BOT: You say? > ")
        mask = ask.replace(" ", "_")
        if mask == mainfunc[0]:
            print("\n" * 100)
            coder.clear_screen()
        else:
            prt = open(mask, "r")
            pr = prt.read()
            print(pr)
            prt = open(mask, "r")
            pr = prt.read()
            print(pr)

This is what I can with text, and I have plan to do same thing with some python modules (like instead of displaying its code, it should execute the code), which search for the module name with the string given by user! It's like unknown module to be executed with name of string.

I have tried getattr and others like {}.format, ... but non worked. I have researched the documentation section of functions and modules, but didn't found anything to help or it was too confusing while I don't know the name of what I am searching for.


Solution

  • Python's exec function will execute a string as raw code, which lets you do something like this:

    module = input("Enter module to import:")
    exec("import " + module)