简体   繁体   中英

How to write something into input() built-in function from code directly

I have a need to fill stdin from code directly when input() is waiting for filling. Is there to do the next:

# Here suppose to be some code that will automatically fill input() below
string = input("Input something: ")
# Or here

I've heard about subprocess.Popen, but I don't understand how to use it in my case. Thank you.

This code is something:

import sys
from io import StringIO


class File(StringIO):
    def __init__(self):
        self._origin_out = sys.stdout
        self._origin_in = sys.stdin
        sys.stdout = self
        sys.stdin = self
        self._in_data = ''
        super(File, self).__init__()

    def write(self, data):
        if data == 'My name is:':
            self._in_data = 'Vasja\n'
        else:
            self._origin_out.write(data)

    def readline(self, *args, **kwargs):
        res = self._in_data
        if res:
            self._in_data = ''
            return res
        else:
            return sys.stdin.readline(*args, **kwargs)

    def __del__(self):
        sys.stdout = self._origin_out
        sys.stdin = self._origin_in


global_out_file = File()

a = input('My name is:')
print('Entered name is:', a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM