0

I am trying to make it possible to import modules for my program. In this code I've received all files but when I try to import the variables, it returns an error.

I don't want to hardcode the import in the code, I want to be able to add new python files without having to manually add them to the code. See the loadCommandFiles() function to see what I tried.

main file:

import tkinter as tk
import os

def main():
    global main_entry
    main_entry = tk.Entry(font = ("Helvetica", 30, "bold"))
    main_entry.pack()
    main_entry.focus_set()
    main_entry.bind('<Return>', entry_parser)

def entry_parser(dontCare):
    entry_string = main_entry.get()

def loadCommandFiles():
    for file in os.listdir(os.getcwd()):
        if file.endswith(".py"):
            if file.endswith("jarvis.py") == False:
                exec("import {}".format(file.replace(".py", "")))
                print(basicCommands.commands)
                
terminal = tk.Tk()
terminal.overrideredirect(True)

terminal.geometry("+{}+{}".format(int(terminal.winfo_screenwidth()/2 - terminal.winfo_reqwidth()/2), int(terminal.winfo_screenheight()/2 - terminal.winfo_reqheight()/2)))

loadCommandFiles()

main()

terminal.mainloop()

basicCommands.py

commands = ["schnitzel"]

error:

NameError: name 'basicCommands' is not defined

Random Davis
  • 6,662
  • 4
  • 14
  • 24
  • You have to `import basicCommands` in the main file. – GaryMBloom Nov 05 '21 at 15:48
  • But you're not even importing `basicCommands`, why would you think that you could use variables in it without importing it? You mentioned that you're importing another file but there's no `import basicCommands`. – Random Davis Nov 05 '21 at 15:49
  • @Gary02127 yea, but I want to be able to add python files without hardcoding them in the main code. – thekingoflorda Nov 05 '21 at 15:49
  • @thekingoflorda then how do you want it to work? You want to just automatically have every .py file in the same directory be imported? That's possible to do with code but you didn't specify that all in your post. – Random Davis Nov 05 '21 at 15:51
  • @RandomDavis yup I did mean that. I've changed the text to better explain this. – thekingoflorda Nov 05 '21 at 15:52
  • Okay but there's already a lot of answered questions on how to do that. What's special about what you want? Does this answer your question? [How to import all submodules?](https://stackoverflow.com/questions/3365740/how-to-import-all-submodules) – Random Davis Nov 05 '21 at 15:56

1 Answers1

0

Start your main program with:

import tkinter as tk
import os
import basicCommands

If you want to import progammatically, try changing the line:

            exec("_import '{}'".format(file.replace(".py", "")))

to:

            __import__(file.replace(".py", ""))
GaryMBloom
  • 5,350
  • 1
  • 24
  • 32