在Python中,重定向输入通常意味着将标准输入(stdin)的数据重定向到程序的其他部分,比如文件、网络连接或其他程序。以下是使用Python重定向输入的几种方法:
使用 `fileinput` 模块
`fileinput` 模块允许你从文件或其他输入流中读取数据,就像从标准输入读取一样。
import fileinput
for line in fileinput.input():
print(line, end='')
使用 `sys.stdout` 重定向到文件
你可以将 `sys.stdout`(标准输出)重定向到一个文件对象,这样原本输出到屏幕的内容就会被写入文件。
import sys
with open('output.txt', 'w') as f:
sys.stdout = f
print('Hello, world!')
sys.stdout = sys.__stdout__ 恢复标准输出
使用 `subprocess` 模块执行命令并重定向输入
`subprocess` 模块允许你启动新的进程,并与之通信。你可以将输入重定向到通过 `subprocess.Popen` 启动的进程。
import subprocess
with open('input.txt', 'r') as f:
process = subprocess.Popen(['your_command'], stdin=f)
process.wait()
自定义类实现输入重定向
你可以创建一个自定义类,重写 `readline` 方法,将读取的数据同时写入到其他目标,比如文件或网络连接。
import sys
class Tee(object):
def __init__(self, input_handle, output_handle):
self.input = input_handle
self.output = output_handle
def readline(self):
result = self.input.readline()
self.output.write(result)
return result
if __name__ == '__main__':
if not sys.stdin.isatty():
sys.stdin = Tee(input_handle=sys.stdin, output_handle=sys.stdout)
a = input('Type something: ')
b = input('Type something else: ')
print('You typed', repr(a), 'and', repr(b))
以上方法展示了如何在Python中实现输入重定向。请根据你的具体需求选择合适的方法