如何读取stdin?一些代码高尔夫挑战需要使用stdin进行输入。
当前回答
非阻塞、字节模式、stdin->stdout:
# pipe.py
import os, sys, time
os.set_blocking(0, False)
sys.stdin = os.fdopen(0, 'rb', 0)
sys.stdout = os.fdopen(1, 'wb', 0)
while 1:
time.sleep(.1)
try: out = sys.stdin.read()
except:
sys.stdout.write(b"E")
continue
if out is None:
sys.stdout.write(b"N")
continue
if not out:
sys.stdout.write(b"_")
break
# working..
out = b"<" + out + b">"
sys.stdout.write(out)
sys.stdout.write(b".\n")
用法:
$ for i in 1 2 3; do sleep 1; printf "===$i==="; done | python3 pipe.py
NNNNNNNNN<===1===>NNNNNNNNN<===2===>NNNNNNNNN<===3===>_.
最小代码:
import os, sys
os.set_blocking(0, False)
fd0 = os.fdopen(0, 'rb', 0)
fd1 = os.fdopen(1, 'wb', 0)
while 1:
bl = fd0.read()
if bl is None: continue
if not bl: break
fd1.write(bl)
在Linux、Python 3.9.2上测试
其他回答
从sys.stdin读取,但要在Windows上读取二进制数据,您需要格外小心,因为sys.stdn是以文本模式打开的,它会损坏\r\n将其替换为\n。
解决方案是,如果检测到Windows+Python2,则将模式设置为二进制,在Python3上使用sys.stdin.buffer。
import sys
PY3K = sys.version_info >= (3, 0)
if PY3K:
source = sys.stdin.buffer
else:
# Python 2 on Windows opens sys.stdin in text mode, and
# binary data that read from it becomes corrupted on \r\n
if sys.platform == "win32":
# set sys.stdin to binary mode
import os, msvcrt
msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
source = sys.stdin
b = source.read()
我在读取通过管道连接到它的套接字时遇到了一些问题。当套接字关闭时,它开始在活动循环中返回空字符串。所以这是我的解决方案(我只在linux中测试过,但希望它能在所有其他系统中运行)
import sys, os
sep=os.linesep
while sep == os.linesep:
data = sys.stdin.readline()
sep = data[-len(os.linesep):]
print '> "%s"' % data.strip()
因此,如果您开始监听套接字,它将正常工作(例如在bash中):
while :; do nc -l 12345 | python test.py ; done
您可以使用telnet调用它,也可以将浏览器指向localhost:1245
关于此:
对于sys.stdin中的行:
我只是在python2.7上尝试了它(按照其他人的建议),用于一个非常大的文件,我不推荐它,正是出于上述原因(很长一段时间没有发生任何事情)。
我最终得到了一个稍微更像蟒蛇的解决方案(它适用于更大的文件):
with open(sys.argv[1], 'r') as f:
for line in f:
然后我可以在本地运行脚本:
python myscript.py "0 1 2 3 4..." # can be a multi-line string or filename - any std.in input will work
有os.读取(0,x)它从表示stdin的0读取xbytes。这是一个无缓冲的读取,比sys.stdin.read()更低级
在使用sys.stdin构建所有函数的基础上,如果至少存在一个参数,还可以执行以下操作来读取参数文件,否则返回到stdin:
import sys
f = open(sys.argv[1]) if len(sys.argv) > 1 else sys.stdin
for line in f:
# Do your stuff
并将其用作
$ python do-my-stuff.py infile.txt
or
$ cat infile.txt | python do-my-stuff.py
甚至
$ python do-my-stuff.py < infile.txt
这将使您的Python脚本表现得像许多GNU/Unix程序,如cat、grep和sed。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录