防止Python显示已输入的输入
在Python中,当我通过终端中的raw_输入更改变量的值时,它会写一行新行,说明它的新值。我想知道是否有办法避免这种情况,因为在用户输入之后,有一个打印函数,它使用之前收到的值。最终,用户将获得两个值:原始值和修改值,而对于我的程序,用户只需查看修改后的值 我使用IDLE编写脚本,然后在终端中执行它们 更新 下面是一个简单的例子。输入是字符串“Hello”,输出应该是“Me:Hello”。在最终结果之前不应该有“你好”防止Python显示已输入的输入,python,input,Python,Input,在Python中,当我通过终端中的raw_输入更改变量的值时,它会写一行新行,说明它的新值。我想知道是否有办法避免这种情况,因为在用户输入之后,有一个打印函数,它使用之前收到的值。最终,用户将获得两个值:原始值和修改值,而对于我的程序,用户只需查看修改后的值 我使用IDLE编写脚本,然后在终端中执行它们 更新 下面是一个简单的例子。输入是字符串“Hello”,输出应该是“Me:Hello”。在最终结果之前不应该有“你好” a = raw_input() print ("Me: " + a) 而
a = raw_input()
print ("Me: " + a)
而且输出应该是公正的
Me: Hello
而不是
Hello
Me: Hello
如果您想让用户看到输入,只需静音
sys.stdout
(这有点像黑客操作):
…如果你把它放到一个函数中,那么它就是你想要的
a、 派克
运行:
yed@rublan $ ~ python a.py
give me input: something I type!!!!!
yed@rublan $ ~
你不必做那样困难的事情,answser非常简单:
chat_respond="you say: "+input("Write here to respond: ")
#i will suppose that you want to write hello
#That will display:
Write here to respond: hello
因为自动打印输入,它将显示变量的字符串,但您在输入之前添加了一些内容,所以它将打印这些内容加上输入
you say: hello
您不需要使用复杂的库或修改模块,只需在储存输入之前添加变量,您也可以这样做:
chat_respond="you say: "
chat_respond+=input("Write here to respond: ")
它也会这样做
再见 我知道这是一个迟来的答案,但这里有一个Python 2+3解决方案(有一点改进): 在
提示符\u demo.py
中:
# coding: utf-8
from __future__ import absolute_import
from __future__ import print_function
import io
import sys
import six.moves
def prompt(msg):
print(msg, end=u'')
orig_out = sys.stdout
try:
sys.stdout = io.StringIO()
return six.moves.input(msg)
finally:
sys.stdout = orig_out
if __name__ == '__main__':
text = prompt(u"Give me input: ")
print(u"Do you mean '{0}'?".format(text))
- 此解决方案使用与Python 2+3兼容的
io.StringIO
- 它还使用
库将six
函数(在Python 3中重命名为raw\u input
)input
试试
在输入过程中如果出现异常,解决方案会更好:它会恢复最后
的原始值sys.stdout
import click
if __name__ == '__main__':
text = click.prompt(u"Give me input: ", prompt_suffix='')
click.echo(u"Do you mean '{0}'?".format(text))
请参阅有关的文档。您能发布您获得的输出和想要的输出吗?显示您引用的实际代码-不清楚到底是什么问题。我添加了一个示例我已经尝试使用此功能,但问题是用户在提交前看不到他键入的文本。这是怎么回事使用
stdout
?)进行黑客攻击。)我加了一个例子那又怎样?!你有没有试过我刚才在回答中输入的密码?它完全按照你的要求工作
# coding: utf-8
from __future__ import absolute_import
from __future__ import print_function
import io
import sys
import six.moves
def prompt(msg):
print(msg, end=u'')
orig_out = sys.stdout
try:
sys.stdout = io.StringIO()
return six.moves.input(msg)
finally:
sys.stdout = orig_out
if __name__ == '__main__':
text = prompt(u"Give me input: ")
print(u"Do you mean '{0}'?".format(text))
import click
if __name__ == '__main__':
text = click.prompt(u"Give me input: ", prompt_suffix='')
click.echo(u"Do you mean '{0}'?".format(text))