防止Python显示输入的内容 [英] Prevent Python from showing entered input

查看:40
本文介绍了防止Python显示输入的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,当我通过终端中的raw_input更改变量的值时,它将写入新行以说明其新值.我想知道是否有一种方法可以避免这种情况,因为在用户输入后立即有一个使用以前接收到的值的打印功能.最终,用户将获得两个值:原始值和修改后的值,而对于我的程序而言,他只需要查看修改后的值即可.

In Python when I change the value of a variable through raw_input in the terminal it would write a new line stating its new value. I wanted to know if there is a way to avoid that because straight after user's input there is a print function which uses the value received before. In the end the user will get both values: original and modified while for the purpose of my program he only has to see the modified.

我使用IDLE编写脚本,然后在终端中执行它们.

I use IDLE to write my scripts and then execute them in terminal.

更新

一个简单的例子如下.输入为字符串"Hello",输出应为"Me:Hello".最终结果前不应有"Hello".

A simple example would be the following. The input is string "Hello" and the output should be "Me: Hello". There should be no "Hello" before the final result.

a = raw_input()
print ("Me: " + a)

输出应该只是

Me: Hello

而不是

Hello
Me: Hello

推荐答案

如果您希望用户看到输入,只需将 sys.stdout 静音(有点hack tho):

if you want user to see the input, just mute sys.stdout (it's a bit hack tho):

>>> from StringIO import StringIO
>>> import sys
>>> orig_out = sys.stdout
>>> print 'give me input: ',
give me input: 
>>> sys.stdout = StringIO()
>>> a = raw_input('')
string I type
>>> sys.stdout = orig_out
>>> a
>>> 'string I type'

...如果将其放入函数中,那么它正是您想要的!

...and if you put this into a function then it's exactly what you want!

a.py

....

def foo():
    orig_out = sys.stdout
    print 'give me input: ',
    sys.stdout = StringIO()
    a = raw_input()
    sys.stdout = orig_out

if __name__ == '__main__':
    foo()

运行:

yed@rublan $ ~ python a.py

give me input: something I type!!!!!

yed@rublan $ ~

这篇关于防止Python显示输入的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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