python怎么重定向输入

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python怎么重定向输入相关的知识,希望对你有一定的参考价值。

控制台重定向

最简单常用的输出重定向方式是利用控制台命令。这种重定向由控制台完成,而与Python本身无关。
Windows命令提示符(cmd.exe)和Linux Shell(bash等)均通过">"或">>"将输出重定向。其中,">"表示覆盖内容,">>"表示追加内容。类似地,"2>"可重定向标准错误。重定向到"nul"(Windows)或"/dev/null"(Linux)会抑制输出,既不屏显也不存盘。
以Windows命令提示符为例,将Python脚本输出重定向到文件(为缩短篇幅已删除命令间空行):
E:\>echo print 'hello' > test.py
E:\>test.py > out.txt
E:\>type out.txt
hello
E:\>test.py >> out.txt
E:\>type out.txt
hello
hello
E:\>test.py > nul

注意,在Windows命令提示符中执行Python脚本时,命令行无需以"python"开头,系统会根据脚本后缀自动调用Python解释器。此外,type命令可直接显示文本文件的内容,类似Linux系统的cat命令。
Linux Shell中执行Python脚本时,命令行应以"python"开头。除">"或">>"重定向外,还可使用tee命令。该命令可将内容同时输出到终端屏幕和(多个)文件中,"-a"选项表示追加写入,否则覆盖写入。示例如下(echo $SHELL或echo $0显示当前所使用的Shell):
[wangxiaoyuan_@localhost ~]$ echo $SHELL
/bin/bash
[wangxiaoyuan_@localhost ~]$ python -c "print 'hello'"
hello
[wangxiaoyuan_@localhost ~]$ python -c "print 'hello'" > out.txt
[wangxiaoyuan_@localhost ~]$ cat out.txt
hello
[wangxiaoyuan_@localhost ~]$ python -c "print 'world'" >> out.txt
[wangxiaoyuan_@localhost ~]$ cat out.txt
hello
world
[wangxiaoyuan_@localhost ~]$ python -c "print 'I am'" | tee out.txt
I am
[wangxiaoyuan_@localhost ~]$ python -c "print 'xywang'" | tee -a out.txt
xywang
[wangxiaoyuan_@localhost ~]$ cat out.txt
I am
xywang
[wangxiaoyuan_@localhost ~]$ python -c "print 'hello'" > /dev/null
[wangxiaoyuan_@localhost ~]$

若仅仅想要将脚本输出保存到文件中,也可直接借助会话窗口的日志抓取功能。
注意,控制台重定向的影响是全局性的,仅适用于比较简单的输出任务。
参考技术A 控制台输入重定向
python test.py < text.txt
将 text.txt中的内容重定向到 test.py
在test.py中可以用 input() 接收输入,每次读取一行
用 sys.stdin.readline(),效果同input()
用sys.stdin.readlines(),读取所有行,返回列表
参考技术B 问的是输入,回答的是输出

Python 输入输出重定向

#基于Python2.7

#若是想Python做到和C++中freopen一样的输入输出重定向效果,即从文件输入输出,可以在程序中加入以下代码

1 import sys
2 sys.stdin=open(in.txt,r)
3 sys.stdout=open(out.txt,w)

 

以上是关于python怎么重定向输入的主要内容,如果未能解决你的问题,请参考以下文章

python 爬网页 遇到重定向怎么处理

Python 输入输出重定向

c语言如何将输入输出流重定向到一个字符串?

C语言输入输出重定向

python 2.7的输入重定向

linux怎么重定向到文件和屏幕