How to display the redirected stdin in Python?

前端 未结 3 1324
再見小時候
再見小時候 2020-12-19 07:10

I\'m starting on a Python project in which stdin redirection is necessary, using code similar to below:

import sys
import StringIO

s = StringIO.StringIO(&quo         


        
3条回答
  •  青春惊慌失措
    2020-12-19 07:57

    EDIT: After reading the other answers and comments I think I have found a good way to really redirect the stdin. Note that I have assumed that you will know the the inputs to the end user's raw_inputs need to be.

    User's Code (Named some_module.py)

    print "running some module with 5 raw_input requests"
    for x in range(5):
        value = raw_input("This is someone else's code asking its (" + str(x) + ") raw_input: ")
        print 'stdin value: ' + value
    

    Your Test Script (Named whatever you like)

        import sys
        class MY_STD_IN( object ):
            def __init__(self, response_list):
                self.std_in_list = response_list
                self.std_in_length = len(response_list)
                self.index = 0
    
            def readline(self):
                value = self.std_in_list[self.index]      
                print value
                if self.index < self.std_in_length -1:
                    self.index += 1
                else:
                    self.index = 0
    
                return value
    
        predetermined_stdin_responses = ['Value 1\r', 'Value 2\r', 'Value 3\r']
        sys.stdin = MY_STD_IN( predetermined_stdin_responses )
    
        import some_module
    

    Running the Script Yields

    running some module with 5 raw_input requests
    This is someone else's code asking its (0) raw_input: Value 1
    stdin value: Value 1
    This is someone else's code asking its (1) raw_input: Value 2
    stdin value: Value 2
    This is someone else's code asking its (2) raw_input: Value 3
    stdin value: Value 3
    This is someone else's code asking its (3) raw_input: Value 1
    stdin value: Value 1
    This is someone else's code asking its (4) raw_input: Value 2
    stdin value: Value 2

    Original Answer

    Not sure if you're looking for such a literal answer but here it is

    import sys
    import StringIO
    
    s = StringIO.StringIO("Hello")
    sys.stdin = s
    a = raw_input("Type something: ")
    sys.stdin = sys.__stdin__
    print(a+"\nYou typed in: "+a)
    

    Yields:

    Type something: Hello

    You typed in: Hello

提交回复
热议问题