如何直接从代码向 input() 内置函数写入内容

发布于 2025-01-14 07:10:43 字数 242 浏览 4 评论 0原文

当 input() 等待填充时,我需要直接从代码填充标准输入。 下一步是否要做:

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

我听说过 subprocess.Popen,但我不明白如何在我的情况下使用它。谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

千年*琉璃梦 2025-01-21 07:10:43

这段代码是这样的:

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)

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文