- -現實 - -
a = "[email protected]"
b = raw_input()
> a # enter
結果:一個
---想要的答案---
a = "[email protected]"
b = raw_input()
> a # enter
結果:“[email protected]”
當我使用它作為輸入時,它可以正常作業,但是當我使用raw_input時,為什么會得到這樣的結果?解決方案是什么?
謝謝你。
uj5u.com熱心網友回復:
對于玩具問題,只需使用input(). 這相當于eval(raw_input()). 如果您甚至有可能不信任輸入,請不要這樣做。任何控制輸入的人都可以在您的程式中執行任意代碼。所以這是一個重大的安全漏洞。
要獲得更安全的方法,請將您希望可訪問的所有值放入字典中,然后通過您的輸入鍵入該字典。這樣做的原因是用戶只能從您給他們的預定義鍵中進行選擇。
例如。
values = {'a': 1, 'b': 2}
key = raw_input()
result = values[key]
print(result)
一個中途的房子可能是使用globals()或locals()。globals()回傳模塊的全域字典并將locals()所有區域變數收集到字典中。這將允許用戶從任何一組名稱中選擇任何名稱。因此他們可能能夠選擇您想要保密的值。
例如。
password = 'foo'
a = 1
b = 2
key = raw_input() # password would be a valid input here
result = vars()[key]
print(result) # so here we would leak the value of password
附帶說明一下,您使用的是 Python 2。Python 2 早已過時,不再接收安全更新。理想情況下,所有新專案都應使用最新版本的 Python 3(例如 3.10)之一。Python 3 只有input(),但它的行為是raw_input()Python 2 中的。
uj5u.com熱心網友回復:
如果您提供輸入,則將其視為字串。
您可以使用字典來保存您的電子郵件,然后使用輸入字串作為鍵來獲取值(Python3 代碼):
your_dict = {'a': '[email protected]'}
b = input()
print(your_dict[b])
#[email protected]
uj5u.com熱心網友回復:
您通過 input() 函式收到的內容將是一個字串。因此您只需要求列印該字串。您可以從此處閱讀有關globals()動態分配變數的更多資訊。
如何動態創建變數?
你可以使用globals()這樣的功能。(input()用于 Python 3。)
a = "[email protected]"
print(globals()[input()])
一種
電子郵件@gmail.com
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/468481.html
標籤:Python python-2.7
