在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