有沒有一種方法可以使用Python eval()
和/或exec()
來保持程序運行之間的狀態,而無需將數據寫入文件或數據庫。 這是更具體的問題。我想編寫一個打印出一個數字的程序,然後在每次再次運行時爲其自身添加1,而不必在文件或數據庫中保留任何變量。 我在最近的一次採訪中被問到了這個問題。 任何幫助表示讚賞。Python eval()和exec()
回答
免責聲明:我做不是建議這樣做。 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)
或者即使是一個成熟的數據庫,如果你有大量的數據。
那麼這是非常好的,我想第一個選擇就是面試官的想法。它很複雜,但它仍然是一個解決方案。 – Stacker
這應該是代碼高爾夫,但它很有趣!
這是根據您的要求使用exec
和eval
的解決方案。
該代碼是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
好啊。我想這是最接近我的想法。 – Stacker
您可以使用文件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
- 1. Python:我應該使用eval,exec還是..?
- 2. NameError:名稱'self'未定義IN EXEC/EVAL
- 3. Bash子進程在執行eval時殺死父進程exec
- 4. 如何在exec或eval中使用無效變量名稱?
- 5. Python exec grep
- 6. exec with';'在python
- 7. EXEC在Python 3
- 8. Python:fork,pipe和exec
- 9. eval函數在Python
- 10. 的Python:動態屬性名稱不生成的exec()或eval()函數
- 11. 全局和本地人在python exec()
- 12. PHP exec()和自定義Python模塊
- 13. Python的拆分EXEC
- 14. GridView和Eval
- 15. NavigateUrl和EVAL
- 16. datasources和eval gridview
- 17. Javascript:new Function()和eval()
- 18. ASPxGridView,ITemplate和Eval
- 19. 使用Python eval評估類
- 20. 在Python中使用eval?
- 21. Exec()和Fork()
- 22. shell exec和mysql
- 23. Rspec和bundle exec
- 24. DUP2()和exec()
- 25. Pipe()fork()和exec
- 26. Eval和href屬性?
- 27. Bash,curl,eval和whitespace
- 28. 使用EXEC()與Python 3.2
- 29. Python的EXEC()的問題
- 30. 的Python等於找到-exec
號爲什麼你會認爲這些會幫助你? 'eval'和'exec'沒有一些與它們相關的魔法永久存儲。 – user2357112
面試官是否問過如何使用eval和exec來做到這一點,或者他只是問一般如何維護狀態,並且您想出了使用eval/exec的想法? – Kevin
這是面試中提供給我的提示的一部分。顯然eval可以以某種方式被用來自我修改代碼,這是我不能想到的。 – Stacker