如何在 python 中重新连接 sys.stdout 到控制台 window?
How to reattach sys.stdout to console window in python?
我的 python 3 涂鸦是这样的:
import io, sys
sys.stdout = io.StringIO()
# no more responses to python terminal funnily enough
我的问题是如何重新附加,因此当我传入 1+1
时,它会 return 和 2
到控制台?
这是在 32 位 python 运行 windows 7 64 位的 python 解释器中。
您正在寻找 sys.__stdout__
:
It can also be used to restore the actual files to known working file objects in case they have been overwritten with a broken object. However, the preferred way to do this is to explicitly save the previous stream before replacing it, and restore the saved object.
我不确定你是如何接受输入的,但这会满足你的要求:
import io, sys
f = io.StringIO()
sys.stdout = f
while True:
inp = input()
if inp == "1+1":
print(inp)
break
sys.stdout = sys.__stdout__
print(eval(f.getvalue()))
或者获取inp的最后一个值:
import io, sys
f = io.StringIO()
sys.stdout = io.StringIO()
while True:
inp = input()
if inp == "1+1":
print(inp)
break
sys.stdout = sys.__stdout__
print(eval(inp))
或遍历标准输入:
import io, sys
sys.stdout = io.StringIO()
for line in sys.stdin:
if line.strip() == "1+1":
print(line)
break
sys.stdout = sys.__stdout__
print(eval(line))
我的 python 3 涂鸦是这样的:
import io, sys
sys.stdout = io.StringIO()
# no more responses to python terminal funnily enough
我的问题是如何重新附加,因此当我传入 1+1
时,它会 return 和 2
到控制台?
这是在 32 位 python 运行 windows 7 64 位的 python 解释器中。
您正在寻找 sys.__stdout__
:
It can also be used to restore the actual files to known working file objects in case they have been overwritten with a broken object. However, the preferred way to do this is to explicitly save the previous stream before replacing it, and restore the saved object.
我不确定你是如何接受输入的,但这会满足你的要求:
import io, sys
f = io.StringIO()
sys.stdout = f
while True:
inp = input()
if inp == "1+1":
print(inp)
break
sys.stdout = sys.__stdout__
print(eval(f.getvalue()))
或者获取inp的最后一个值:
import io, sys
f = io.StringIO()
sys.stdout = io.StringIO()
while True:
inp = input()
if inp == "1+1":
print(inp)
break
sys.stdout = sys.__stdout__
print(eval(inp))
或遍历标准输入:
import io, sys
sys.stdout = io.StringIO()
for line in sys.stdin:
if line.strip() == "1+1":
print(line)
break
sys.stdout = sys.__stdout__
print(eval(line))