![](/img/trans.png)
[英]How can I append something to a result of a function and store that in a Variable in python
[英]How can I store the result of a function stored in variable as a string?
我正在使用boto3 python sdk開發用於AWS快照的開源腳本。
我有一個返回json的函數,其中包含一個函數:
datetime.datetime(2017, 11, 3, 21, 2, 27, tzinfo=tzlocal())
當我存儲json的結果時,它將存儲該函數字符串,而不是該函數的結果。
如何獲取python3執行該功能?
(當我打印該字典時間時,這很奇怪,它顯示正確)
這是我的字典的樣子:
{'snap-05c84': datetime.datetime(2017, 11, 3, 22, 4, 48, tzinfo=tzlocal()), 'snap-08bcb': datetime.datetime(2017, 11, 3, 21, 2, 27, tzinfo=tzlocal())}
構建字典的代碼是:
for snap in snaps['Snapshots']:
snap_id=snap['SnapshotId']
start_time=snap['StartTime']
snap_times[snap_id]=start_time
提前致謝!!!
您可以使用eval執行代碼並獲取結果。
但是,當我查看您的示例時,為什么將那個datetime對象作為字符串? 也許您希望在那里已經擁有價值。 您可以為此使用處理程序:
import datetime
import json
def datetime_handler(x):
if isinstance(x, datetime.datetime):
return x.isoformat()
raise TypeError("Unknown type")
json.dumps(data, default=datetime_handler)
如果您不喜歡isoformat,則可以使用strftime 。
如果我對您的理解正確,那么您有一個函數名稱,該名稱存儲為字符串。 如果是這種情況,您可以使用此處提供的解決方案,從帶有函數名稱的字符串中調用模塊的函數以使用該函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.