java 清除stdin缓冲区,Python子脚本消耗了所有的stdin

在bash脚本中运行python脚本时,我发现了raw_input / readline的某些奇怪行为.

简而言之,当一次将所有stdin(每个条目用换行分隔)传递给父脚本时,bash子脚本将仅采用其所需的stdin,而python子脚本将消耗所有stdin,不留任何内容为下一个孩子.我想出一个简单的例子来说明我的意思:

父脚本(parent.sh)

#!/bin/bash

./child.sh

./child.sh

./child.py

./child.py

Bash子脚本(child.sh)

#!/bin/bash

read -a INPUT

echo "sh: got input: ${INPUT}"

Python子脚本(child.py)

#!/usr/bin/python -B

import sys

INPUT = raw_input()

print "py: got input: {}".format(INPUT)

预期结果

./parent.sh <<< $'aa

bb

cc

dd'

>> sh: got input: aa

>> sh: got input: bb

>> py: got input: cc

>> py: got input: dd

实际结果

./parent.sh <<< $'aa

bb

cc

dd

'

>> sh: got input: aa

>> sh: got input: bb

>> py: got input: cc

>> Traceback (most recent call last):

>> File "./child.py", line 5, in

>> INPUT = raw_input()

>> EOFError: EOF when reading a line

raw_input似乎清除了stdin中的所有其余行.使用sys.stdin.readline代替raw_input不会引发EOFError,但是接收到的输入是一个空字符串,而不是预期的’dd’.

这是怎么回事如何避免这种行为,以便最后一个子脚本收到预期的输入?

编辑:可以肯定的是,我向stdin添加了几行,结果是相同的:

./parent.sh <<< $'aa

bb

cc

dd

ff

ee

'

>> sh: got input: aa

>> sh: got input: bb

>> py: got input: cc

>> Traceback (most recent call last):

>> File "./child.py", line 5, in

>> INPUT = raw_input()

>> EOFError: EOF when reading a line

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值