簡體   English   中英

在raw_input上使用Python的輸入是否有用?

[英]Is it ever useful to use Python's input over raw_input?

我目前教一年級大學生python,我很驚訝地發現,我的一些學生決定使用(並且被奇怪的行為混淆)看似無害的input功能,隱藏了對它后面的eval的調用。

所以我的問題是,為什么input函數調用eval ,這對於用raw_input東西會有什么用呢? 我知道Python 3已經改變了,但它首先似乎是一個不尋常的設計決定。

Python 2.x輸入函數文檔

在raw_input上使用Python 2的輸入是否有用?

沒有。


input()評估用戶給出的代碼。 它將Python的全部功能掌握在用戶手中。 使用生成器表達式/列表__import____import__if/else運算符,可以使用單個表達式實現Python所能做的任何事情。 惡意用戶可以使用input()刪除文件( __import__('os').remove('precious_file') ),monkeypatch程序的其余部分( setattr(__import__('__main__'), 'function', lambda:42) ),......任何事情。

普通用戶不需要使用所有高級功能。 如果您不需要表達式,使用ast.literal_eval(raw_input()) -的literal_eval功能是安全的。

如果您是為高級用戶編寫的,請為他們提供更好的輸入代碼的方法。 插件,用戶模塊等 - 具有完整Python語法的東西,而不僅僅是功能。

如果你完全確定你知道自己在做什么,請說eval(raw_input()) eval尖叫着“我很危險!” 受過訓練的眼睛。 但是,你很可能不會需要這個。


input()是Python 3正在解決的舊設計錯誤之一。

Python Input函數返回一個對象,該對象是評估表達式的結果。 raw_input函數返回一個字符串

name = "Arthur"
age = 45

first = raw_input("Please enter your age ")
second = input("Please enter your age again ")

# first will always contain a string

# second could contain any object and you can even
# type in a calculation and use "name" and "age" as
# you enter it at run time ...

print "You said you are",first
print "Then you said you are",second

運行的例子:

示例:1

Prompt$ python yraw 
Please enter your age 45 
Please enter your age again 45 
You said you are 45 Then you said you are 45

示例:2

Prompt$ python yraw
Please enter your age 45 + 7
Please enter your age again 45 + 7
You said you are 45 + 7 Then you said you are 52 
Prompt$

問:為什么輸入函數調用eval?

A.考慮用戶在輸入中輸入表達式'45 + 7'的情況,與python 2.x中的raw_input相比,輸入將給出正確的結果

input幾乎只用作交互式python shell的構建塊。 你肯定是正確的,它的工作方式令人驚訝,並且它的內容非常特定 - 我認為它是從Python 3中刪除的原因。

raw_input更好,它總是返回用戶的輸入而不做任何更改。 相反, input()函數會嘗試將您輸入的內容轉換為Python代碼,並且存在安全問題,因此您應該避免使用它。

在實際程序中,不要使用input() ,使用處理您期望的特定輸入格式的東西來解析輸入,而不是通過將輸入評估為Python代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM