猿问

Python-如何从外部文件调用代码

我修改了这个问题,使其更加简单。


我正在python 3.x中运行程序。我希望该程序打开文件名example.py并在其中运行代码。这是文件的内容:


#example1.py

print('hello world')


#example2.py

    print('hello world 2')


#main.py

someMagicalCodeHere(executes example2.py)

#prints hello world

我需要执行此操作而不将其导入文件。


导入文件的问题在于它们是在main.py中预先声明的。我的main.py将创建example1.py,example2.py等并用代码填充它们,然后根据需要参考它们。可能有成千上万。


这是一个大型项目的一部分,我们正在尝试切换到新语言。我们还不了解python,我们需要这个概念才能继续学习该语言。


我试过exec(example.py)


我已经尝试使用open('example.py','r')作为ex:ex.read()


在此先感谢您的回答,并感谢所有迄今已回答的人。


jeck猫
浏览 277回答 3
3回答

ITMISS

我假设您有某种将字符串转换为此类答案的函数,或者可能是字典。否则,解决该问题的方法将超出NLP当前的进展范围。def ask_question_and_get_response(question=None):&nbsp; &nbsp; answer = input(question)&nbsp; &nbsp; return answer我还必须假设您有一种方法可以转换原始问题,例如“您叫什么名字?” ,然后用户可能会问您的机器人“我叫什么名字?” 。让该函数如下所示:def get_reflex_question(question):&nbsp; &nbsp; <your implementation>&nbsp; &nbsp; return reflex_question有了这两个选项,我们可以创建一个文件(如果尚不存在),并向其中写入可以解释为Python代码的文件。def make_code(answer, reflex_question)&nbsp; &nbsp; with open("filename", "a") as file:&nbsp; &nbsp; &nbsp; &nbsp; file.write("\n")&nbsp; &nbsp; &nbsp; &nbsp; file.write("if userBoxAsks == %s:\n\t" % (reflex_question))&nbsp; &nbsp; &nbsp; &nbsp; file.write("print(answer)")它将输出代码到您的命名文件中。要运行该文件,您可以使用subprocess模块(请阅读文档),或简单地将您的文件作为模块本身导入。每当您更新文件时,都可以重新加载导入,以便新代码也可以运行。在Python3.x中,您可以importlib.reload(filename)刷新导入。
随时随地看视频慕课网APP

相关分类

Python
我要回答