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

Python - How to call code from an external file

我修改了这个问题,让它变得更简单。

我正在 运行python3.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,我们需要这个概念可行才能继续学习这门语言。

我试过了 执行(example.py)

我试过了 以 open('example.py', 'r') 作为例子: ex.read()

在此先感谢您的回答,并感谢到目前为止所有回答的人。

我假设您有某种函数可以将字符串转换为此类答案,或者可能是字典。否则这个问题的解决方案将超出NLP当前进展的范围。

def ask_question_and_get_response(question=None): answer = input(question) return answer

我还必须假设您有办法将原始问题(例如 "What is your name?" 转换为用户可能反过来问您的机器人的问题, "What is my name?"。让该函数如下所示:

def get_reflex_question(question):
    <your implementation>
    return reflex_question

有了这两个在手,我们就可以创建一个文件(如果这个文件不存在的话),并向其中写入可以解释为 Python 代码的内容。

def make_code(answer, reflex_question)
    with open("filename", "a") as file:
        file.write("\n")
        file.write("if userBoxAsks == %s:\n\t" % (reflex_question))
        file.write("print(answer)")

这会将代码输出到您命名的文件中。 要 运行 该文件,您可以使用 subprocess 模块(阅读文档),或者简单地将您的文件作为模块本身导入。 每当您更新文件时,您都可以 重新加载 导入,以便新代码也 运行 。在 Python3.x 中,您可以 importlib.reload(filename) 刷新导入。

好吧,经过深思熟虑,寻找和寻找,我通过实验发现,找到了我自己问题的答案。

#c:\one.py
print('hello world')

#c:\main.py
import os.path


filename = "c:\one.py"

if not os.path.isfile(filename):
    print ('File does not exist.')
else:

    with open(filename) as f:
        content = f.read().splitlines()

    for line in content:
        exec(line)

Returns(不带引号)'Hello World'

请注意,这些解决方案不安全且存在风险。所以显然是为了 play/test 目的

Python 2:

execfile('example2.py') 

Python 3:

with open('example2.py') as f:
    exec(f.read())