Python的fileinput如何接受输入

时间:2019-02-17 16:24:20

标签: python input

我想知道fileinput.input()如何接受交互式输入。

我看了看- https://github.com/python/cpython/blob/master/Lib/fileinput.py

这是内部行读取器的外观:

def _readline(self):
    if not self._files:
        if 'b' in self._mode:
            return b''
        else:
            return ''
    self._filename = self._files[0]
    self._files = self._files[1:]
    self._startlineno = self.lineno()
    self._filelineno = 0
    self._file = None
    self._isstdin = False
    self._backupfilename = 0
    if self._filename == '-':
        self._filename = '<stdin>'
        if 'b' in self._mode:
            self._file = getattr(sys.stdin, 'buffer', sys.stdin)
        else:
            self._file = sys.stdin
        self._isstdin = True
    else:
        if self._inplace:
            self._backupfilename = (
                os.fspath(self._filename) + (self._backup or ".bak"))
            try:
                os.unlink(self._backupfilename)
            except OSError:
                pass
            # The next few lines may raise OSError
            os.rename(self._filename, self._backupfilename)
            self._file = open(self._backupfilename, self._mode)
            try:
                perm = os.fstat(self._file.fileno()).st_mode
            except OSError:
                self._output = open(self._filename, "w")
            else:
                mode = os.O_CREAT | os.O_WRONLY | os.O_TRUNC
                if hasattr(os, 'O_BINARY'):
                    mode |= os.O_BINARY

                fd = os.open(self._filename, mode, perm)
                self._output = os.fdopen(fd, "w")
                try:
                    if hasattr(os, 'chmod'):
                        os.chmod(self._filename, perm)
                except OSError:
                    pass
            self._savestdout = sys.stdout
            sys.stdout = self._output
        else:
            # This may raise OSError
            if self._openhook:
                self._file = self._openhook(self._filename, self._mode)
            else:
                self._file = open(self._filename, self._mode)
    self._readline = self._file.readline  # hide FileInput._readline
    return self._readline()

我不确定该怎么做,并且很好奇要在这里实际处理交互式输入,因为我看不到内置input()的调用。

实际上是什么fileinput.input()中生成用户提示的?

1 个答案:

答案 0 :(得分:1)

在不提供任何参数的情况下,它会调用sys.stdin.readline方法。如果未提供任何参数,则_readline方法将如下所示。

def _readline(self):
        if self._filename == '-': # when no `files` parameter is supplied `self._filename` will be `-`
                self._file = sys.stdin
        self._readline = self._file.readline  # hide FileInput._readline
        return self._readline() # invoke the sys.stdin.readline()