我们正在使用一些没有源代码的已编译python代码。代码提示用户输入,我们正在尝试使该部分自动化。
基本上要求输入用户名,密码,然后根据特定情况询问一些各种问题。我不知道编译后的函数是否正在使用raw_input,input或其他东西。
我已经能够使用StringIO替换带有用户名和密码的stdin,并且可以使用自己的类替换stdout并确定出现哪个提示,但是当我有选择地将数据放入基于stdin的情况时,我感到很困惑关于我从stdout读取的内容。
import sys
import re
from StringIO import StringIO
def test():
overwrite = raw_input("The file exists, overwrite? ")
notify = raw_input("This file is marked for notifies. Notify?")
sys.stdout.write("Overwrite: %s, Notify: %s" % (overwrite,notify))
class Catcher(object):
def __init__(self):
pass
def write(self, msg):
if re.search("The file exists, overwrite", msg):
# put data into stdin
if re.search("The file is marked for notification", msg):
# put data into stdin
sys.stdout = Catcher()
test()
我不能只是预加载一个StringIO对象,因为问题可能会因情况而异,但是我需要自动将其输入标准输入,因为他们正试图将其放入自动生成系统中,因此它们将提供默认值通过命令行回答出现的任何问题。
如果在调用编译函数之前将stdin设置为空的StringIO对象,则EOF只会出错-不知道如何使其等待输入。
像这样:
import sys
import re
from StringIO import StringIO
def test():
overwrite = raw_input("The file exists, overwrite? ")
notify = raw_input("This file is marked for notifies. Notify?")
sys.__stdout__.write("Overwrite: %s, Notify: %s" % (overwrite,notify))
class Catcher(object):
def __init__(self, stdin):
self.stdin = stdin
def write(self, msg):
if re.search("The file exists, overwrite", msg):
self.stdin.write('yes\n')
if re.search("The file is marked for notification", msg):
self.stdin.write('no\n')
sys.stdin = StringIO()
sys.stdout = Catcher(sys.stdin)
test()
产生:
Traceback (most recent call last):
File "./teststdin.py", line 25, in <module>
test()
File "./teststdin.py", line 8, in test
overwrite = raw_input("The file exists, overwrite? ")
EOFError: EOF when reading a line
有任何想法吗?
最佳答案
如果要从刚刚写入的StringIO
中读取内容,则必须先将其后退到开始写入的位置。
另外,您的第二次搜索将测试错误的字符串。
这应该工作:
import sys
import re
from StringIO import StringIO
def test():
overwrite = raw_input("The file exists, overwrite? ")
notify = raw_input("This file is marked for notifies. Notify?")
sys.__stdout__.write("Overwrite: %s, Notify: %s" % (overwrite,notify))
class Catcher(object):
def __init__(self, stdin):
self.stdin = stdin
def write(self, msg):
if re.search("The file exists, overwrite?", msg):
self.stdin.truncate(0)
self.stdin.write('yes\n')
self.stdin.seek(0)
if re.search("This file is marked for notifies. Notify?", msg):
self.stdin.truncate(0)
self.stdin.write('no\n')
self.stdin.seek(0)
sys.stdin = StringIO()
sys.stdout = Catcher(sys.stdin)
test()