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

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

问题描述

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

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

更新

一个简单的例子如下.输入是字符串Hello",输出应该是Me: Hello".在最终结果之前应该没有你好".

a = raw_input()打印(我:"+一个)

输出应该只是

我:你好

而不是

你好我:你好

解决方案

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

<预><代码>>>>从 StringIO 导入 StringIO>>>导入系统>>>orig_out = sys.stdout>>>打印'给我输入:',给我输入:>>>sys.stdout = StringIO()>>>a = raw_input('')我输入的字符串>>>sys.stdout = orig_out>>>一个>>>'我输入的字符串'

...如果你把它放到一个函数中,那么它正是你想要的!

a.py

<代码>....定义 foo():orig_out = sys.stdout打印'给我输入:',sys.stdout = StringIO()a = raw_input()sys.stdout = orig_out如果 __name__ == '__main__':富()

运行:

yed@rublan $ ~ python a.py给我输入:我输入的东西!!!!!yed@rublan $ ~

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.

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

Update

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)

And the output should be just

Me: Hello

rather than

Hello
Me: Hello

解决方案

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()

running:

yed@rublan $ ~ python a.py

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

yed@rublan $ ~

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

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