在 raw_input 上使用 Python 的输入有用吗? [英] Is it ever useful to use Python's input over raw_input?

查看:27
本文介绍了在 raw_input 上使用 Python 的输入有用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前教大学一年级学生 python,我惊讶地发现看似无害的 input 函数,我的一些学生决定使用(并且被奇怪的行为弄糊涂了), 在其后面隐藏了对 eval 的调用.

I currently teach first year university students python, and I was surprised to learn that the seemingly innocuous input function, that some of my students had decided to use (and were confused by the odd behaviour), was hiding a call to eval behind it.

所以我的问题是,为什么 input 函数调用 eval,这对使用 raw_input?我知道这在 Python 3 中已经改变,但首先这似乎是一个不寻常的设计决定.

So my question is, why does the input function call eval, and what would this ever be useful for that it wouldn't be safer to do with raw_input? I understand that this has been changed in Python 3, but it seems like an unusual design decision in the first place.

Python 2.x 输入函数文档

推荐答案

使用 Python 2 的输入而不是 raw_input 有用吗?

Is it ever useful to use Python 2's input over raw_input?

没有.

input() 评估用户提供的代码.它将 Python 的全部功能交到用户手中.使用生成器表达式/列表推导式,__import__,以及if/else 运算符,实际上 Python 可以做的任何事情都可以通过一个表达式来实现.恶意用户可以使用 input() 删除文件 (__import__('os').remove('precious_file')),monkeypatch 程序的其余部分 (setattr(__import__('__main__'), 'function', lambda:42)), ... 任何东西.

input() evaluates the code the user gives it. It puts the full power of Python in the hands of the user. With generator expressions/list comprehensions, __import__, and the if/else operators, literally anything Python can do can be achieved with a single expression. Malicious users can use input() to remove files (__import__('os').remove('precious_file')), monkeypatch the rest of the program (setattr(__import__('__main__'), 'function', lambda:42)), ... anything.

普通用户不需要使用所有高级功能.如果您不需要表达式,请使用 ast.literal_eval(raw_input()) - literal_eval 函数是安全的.

A normal user won't need to use all the advanced functionality. If you don't need expressions, use ast.literal_eval(raw_input()) – the literal_eval function is safe.

如果您是为高级用户编写代码,请为他们提供更好的输入代码方式.插件、用户模块等——具有完整 Python 语法的东西,而不仅仅是功能.

If you're writing for advanced users, give them a better way to input code. Plugins, user modules, etc. – something with the full Python syntax, not just the functionality.

如果您绝对确定自己知道自己在做什么,请说eval(raw_input()).eval 尖叫着我很危险!"训练有素的眼睛.但是,您可能永远不需要这个.

If you're absolutely sure you know what you're doing, say eval(raw_input()). The eval screams "I'm dangerous!" to the trained eye. But, odds are you won't ever need this.

input() 是 Python 3 正在解决的旧设计错误之一.

input() was one of the old design mistakes that Python 3 is solving.

这篇关于在 raw_input 上使用 Python 的输入有用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆