Skip to content Skip to sidebar Skip to footer

Python Stringio - Selectively Place Data Into Stdin

We're using a bit of compiled python code that we don't have the source to. The code prompts for user input and we're trying to automate that portion. Basically asks for username,

Solution 1:

If you want to read from a StringIO you've just written to, you have to rewind it first to the position you've started writing. Also, your second search tests for the wrong string.

This should work:

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()

Solution 2:

Here's a solution that avoid StringIO entirely:

import sys
import re

classCatcher(object):
    def__init__(self, handler):
        self.handler = handler
        self.inputs = []

    def__enter__(self):
        self.__stdin  = sys.stdin
        self.__stdout = sys.stdout
        sys.stdin = self
        sys.stdout = self

    def__exit__(self, type, value, traceback):
        sys.stdin  = self.__stdin
        sys.stdout = self.__stdout

    defwrite(self, value):
        result = self.handler(value)
        if result:
            self.inputs = [result] + self.inputs

    defreadline(self):
        return self.inputs.pop()

Used as:

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))


@Catcher
def exist_notify(msg):
    if re.search("The file exists, overwrite", msg):
        return 'yes'
    if re.search("This file is marked for notifies", msg):
        return 'no'

with exist_notify:
    test()

Post a Comment for "Python Stringio - Selectively Place Data Into Stdin"