簡體   English   中英

Python-如何從外部文件調用代碼

[英]Python - How to call code from an external file

我修改了這個問題,使其更加簡單。

我正在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()

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

我假設您有某種將字符串轉換為此類答案的函數,或者可能是字典。 否則,解決該問題的方法將超出NLP當前的進展范圍。

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

我還必須假定您有辦法轉換原始問題,例如“您叫什么名字?” ,然后用戶可能會問您的機器人叫什么名字?” 讓該函數如下所示:

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)

返回(不帶引號)“ Hello World”

請注意,這些解決方案並不安全,並且被認為具有風險。 所以顯然是為了玩/測試目的

Python 2:

execfile('example2.py') 

Python 3:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM