【发布时间】:2015-09-21 16:25:01
【问题描述】:
我的 python 代码如下所示:
def test():
pipe = sp.Popen( ["test.sh"], stdin=sp.PIPE)
data = "".join([chr((s)%17) for s in range(0,33)])
os.write(pipe.stdin.fileno(), data)
pipe.stdin.write("endoffile")
if __name__ == "__main__":
test()
它调用以下简单的 bash shell 脚本,该脚本只是将标准输入写入文件(脚本称为 test.sh)
#!/bin/bash
VALUE=$(cat)
echo "$VALUE" >> /tmp/test.txt
当我运行 python 代码时,我希望 test.txt 包含两次值 0x01..0x10,然后是字符串“endofile”
但是这里是文件的十六进制转储:
0000000: 0102 0304 0506 0708 090a 0b0c 0d0e 0f10 ................
0000010: 0102 0304 0506 0708 090a 0b0c 0d0e 0f65 ...............e
0000020: 6e64 6f66 6669 6c65 0a ndoffile.
似乎缺少一个字节(0x10)。
我在这里错过了什么?
--- 更新
将 test() 函数更改为:
def test():
pipe = sp.Popen( ["test.sh"], stdin=sp.PIPE)
data = "".join([chr((s)%16+1) for s in range(0,32)])
os.write(pipe.stdin.fileno(), data)
pipe.stdin.write("endoffile")
似乎解决了这个问题。 这似乎与将 chr(0) 发送到管道有关。
【问题讨论】:
标签: python bash pipe subprocess