2017-02-03 127 views
0

有沒有一種方法可以使用Python eval()和/或exec()來保持程序運行之間的狀態,而無需將數據寫入文件或數據庫。 這是更具體的問題。我想編寫一個打印出一個數字的程序,然後在每次再次運行時爲其自身添加1,而不必在文件或數據庫中保留任何變量。 我在最近的一次採訪中被問到了這個問題。 任何幫助表示讚賞。Python eval()和exec()

+0

號爲什麼你會認爲這些會幫助你? 'eval'和'exec'沒有一些與它們相關的魔法永久存儲。 – user2357112

+0

面試官是否問過如何使用eval和exec來做到這一點,或者他只是問一般如何維護狀態,並且您想出了使用eval/exec的想法? – Kevin

+0

這是面試中提供給我的提示的一部分。顯然eval可以以某種方式被用來自我修改代碼,這是我不能想到的。 – Stacker

回答

1

免責聲明:我做不是建議這樣做。 99.999%的時間,最好將可序列化的信息存儲在自己的文件中。

如果「不寫入數據到文件」,「不將數據寫入自己的文件」,你的意思是, 可以打開正在運行的Python文件,並就地重寫數據:

import re 

x = 0 
print "The value of the variable x is: {}".format(x) 

with open("test.py") as file: 
    data = file.read() 

data = re.sub(r"x = (\d+)", "x = {}".format(x+1), data) 

with open("test.py", "w") as file: 
    file.write(data) 

現在,每個後續執行的值都會改變。

C:\Users\Kevin\Desktop>test.py 
The value of the variable x is: 0 

C:\Users\Kevin\Desktop>test.py 
The value of the variable x is: 1 

C:\Users\Kevin\Desktop>test.py 
The value of the variable x is: 2 

C:\Users\Kevin\Desktop>test.py 
The value of the variable x is: 3 

C:\Users\Kevin\Desktop>test.py 
The value of the variable x is: 4 

但再次,它最好只是保持在一個單獨的文件中的數據,例如使用shelve

import shelve 

d = shelve.open("data.dat") 
if "x" not in d: 
    d["x"] = 0 

print "The value of x is: {}".format(d["x"]) 
d["x"] += 1 

或者,如果你珍惜或許JSON人類可讀性:

import json 

try: 
    with open("data.dat") as file: 
     d = json.load(file) 
except IOError: #first execution. file doesn't exist yet. 
    d = {"x":0} 

print "The value of x is: {}".format(d["x"]) 
d["x"] += 1 

with open("data.dat", "w") as file: 
    json.dump(d, file) 

或者即使是一個成熟的數據庫,如果你有大量的數據。

+0

那麼這是非常好的,我想第一個選擇就是面試官的想法。它很複雜,但它仍然是一個解決方案。 – Stacker

1

這應該是代碼高爾夫,但它很有趣!
這是根據您的要求使用execeval的解決方案。
該代碼是15行長,對每次運行一個附加行(z=1)被添加到.py文件
,什麼是印刷是number of lines in file now - 15,因而在每次運行時的打印增量

initial_num_lines = 15 
def get_lines_in_file(): 
    f = open('evalexec.py', 'r') 
    num_lines = len(f.readlines()) 
    return num_lines 

lines = str(get_lines_in_file() - initial_num_lines) 
print eval(lines+'+1') 
exec_code = ''' 
f = open('evalexec.py', 'a') 
f.write("\\nz=1") 
f.close() 
''' 
exec(exec_code) 

OUTPUT:

>python evalexec.py 
0 

>python evalexec.py 
1 

>python evalexec.py 
2 

>python evalexec.py 
3 
+0

好啊。我想這是最接近我的想法。 – Stacker

1

您可以使用文件stats使用os.utime跟蹤的最後修改值(這是一個整數),並對其進行更新每次運行:

import os 

last_modified = os.stats(__file__).st_mtime 
print(int(last_modified)) 

os.utime(__file__, (last_modified, last_modified + 1)) 

連續運行:

Petes-Mac:~ petewood$ python inc.py 
1486149574 
Petes-Mac:~ petewood$ python inc.py 
1486149575 
Petes-Mac:~ petewood$ python inc.py 
1486149576