Skip to main content
 首页 » 编程设计

python之如何在 Python 脚本中输入答案

2024年11月01日7lhb25

def foo(): 
    return raw_input("answer this question: ") 
 
 
# some code here then 
foo() 
# some more code here 

foo 是第 3 方函数调用,它会以某种方式触发输入。

如果我们事先知道答案,我们如何在其中输入答案? 没有弹出;我什至没有运行脚本文件。我能想到的一种方法是使用线程?

请您参考如下方法:

有点不正统,但你可以猴子补丁sys.stdin:

# We're going to monkey-patch stdin 
import sys 
from cStringIO import StringIO 
old = sys.stdin 
sys.stdin = StringIO('hello') 
 
# Now read from stdin 
result = raw_input('foo') 
 
# And replace the regular stdin 
sys.stdin = old 

这就像您键入“hello”作为 raw_input 的输入一样。当然,您不是自己调用 raw_input,而是调用您的 foo 函数。我想如果我不止一次这样做,我会使用上下文管理器来确定我撤消了猴子补丁:

import sys 
from cStringIO import StringIO 
 
class PatchStdin(object): 
    def __init__(self, value): 
        self._value = value 
        self._stdin = sys.stdin 
    def __enter__(self): 
        # Monkey-patch stdin 
        sys.stdin = StringIO(self._value) 
        return self 
    def __exit__(self, typ, val, traceback): 
        # Undo the monkey-patch 
        sys.stdin = self._stdin 
 
 
# Usage 
with PatchStdin('Dan'): 
    name = raw_input('What is your name? ') 
    print 'Hello, %s' % name