我的意思是這個標題是前:
def write_to_file(*params):
with open(path, 'r ', encoding="utf-8") as file:
content = file.read()
file.seek(0)
# custom code via func parameters to be executed
# for example *params will be ["file.write("test" '\n')", "]
# and here will be like for loop that goes through the params ?
# for code in params:
#code.execute() ?
file.truncate()
希望我解釋得很好,只是想知道你是否可以做到這一點。
// 編輯(更好的解釋):我想將字串轉換為代碼可執行檔案,“print(x)”-> print(x) 將在函式中呼叫。
uj5u.com熱心網友回復:
傳遞函式本身:
def write_to_file(func):
with open(path, 'r ', encoding="utf-8") as file:
content = file.read()
file.seek(0)
func()
file.truncate()
def func():
print("foo")
write_to_file(func)
uj5u.com熱心網友回復:
如果您只需要從字串執行代碼(讀取檔案的內容.read()并以單行或多行字串的形式回傳它們),那么您可以簡單地使用eval () 函式。
eval() 是一個內置的 Python 函式,可以計算其中給出的任何運算式,并且運算式中的任何錯誤也會相應地在控制臺上拋出。該函式只計算給定的單行運算式,不支持賦值和其他相關運算子。出于其他目的,您可能還想使用exec () Python 函式。
我最初想評論它,但在發布它時我缺少 2 的聲譽分數,所以必須在這里發布它作為答案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/412396.html
標籤:
