Exec 不适用于函数和变量

Exec doesn't work with functions and variables

我正在制作一个适用于 .py 文件的插件系统。当我用那个插件(.py 文件)执行 exec() 并且它有一个函数或变量时,它会给出一个 NameError。

NameError: name 'editor_nf' is not defined

我已经用谷歌搜索过了,但没有找到任何对我有帮助的东西。

我只做了:

plugin = open("plugin.py","r").read()
exec(plugin)

并且 plugin.py 文件是:

import tkinter as tk

def editor_nf():
    enf = tk.Tk()
    enf.title("New file")
    enf.config(bg="white")
    enf.geometry("500x500")

    enf.mainloop()

def editor():
    editor = tk.Tk()
    editor.title("Website Editor")
    editor.config(bg="white")
    editor.geometry("1400x700")

    editor_nf_btn = tk.Button(editor,text="New file",bg="gray",fg="black",font="Arial",command=editor_nf)
    editor_nf_btn.grid(row=0,column=0)

    editor.mainloop()

editor()

所以我希望它与函数一起工作,以便人们可以创建工作函数。

我不想让它显示:

NameError: name 'editor_nf' is not defined

dcg 回答了,它有帮助,但后来我将它转换为 exe,我得到了这个

让我举一个简单的例子来说明我在评论中告诉你的内容。这是我的文件夹结构:

/sample
   - plugins/
       - __init__.py # not necessary, but maybe you want to apply some logic 
                     # before importing the plugins
       - plugin1.py
       - plugin2.py
       - plugin3.py
   - __init__.py
   - test.py

每个插件都打印它是什么插件(例如,print('plugin 1'))。 test.py如下:

import os

if __name__ == '__main__':
    # load plugins
    plugins = [p for p in os.listdir('plugins') if not p.startswith('_')]
    for p in plugins:
        __import__('plugins.'+p[:-3])

输出为:

plugin 1
plugin 2
plugin 3

这意味着我使用 __import__ 成功导入了所有这些模块(插件)。请注意,__import__ returns 是对导入模块的引用,因此您可以存储它供以后操作。希望对您有所帮助!

我说我编辑它时出现了错误之类的东西,但我自己修复了它。感谢您的帮助!