簡體   English   中英

如何直接從代碼向內置 function 中寫入一些內容

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

當 input() 等待填充時,我需要直接從代碼中填充標准輸入。 有沒有做下一個:

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

我聽說過 subprocess.Popen,但我不知道如何在我的案例中使用它。 謝謝你。

這段代碼是:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM