在Python中,当我通过终端中的raw_input更改变量的值时,它会写入一个新行来说明其新值。我想知道是否有办法避免这种情况,因为在用户输入之后立即有一个打印函数,它使用之前收到的值。最后,用户将获得两个值:原始值和修改后的值,而出于我的程序的目的,他只需要看到修改后的值。
我使用 IDLE 编写脚本,然后在终端中执行它们。
更新
一个简单的例子如下。输入是字符串“Hello”,输出应该是“Me:Hello”。最终结果之前不应该有“Hello”。
a = raw_input()
print ("Me: " + a)
Run Code Online (Sandbox Code Playgroud)
输出应该只是
Me: Hello
Run Code Online (Sandbox Code Playgroud)
而不是
Hello
Me: Hello
Run Code Online (Sandbox Code Playgroud)
如果你想让用户看到输入,只需静音sys.stdout(这有点黑客):
>>> 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'
Run Code Online (Sandbox Code Playgroud)
...如果您将其放入一个函数中,那么它正是您想要的!
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()
Run Code Online (Sandbox Code Playgroud)
跑步:
yed@rublan $ ~ python a.py
give me input: something I type!!!!!
yed@rublan $ ~
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18327 次 |
| 最近记录: |