gpt4 book ai didi

python - 当我写入 python 子进程标准输入管道时,为什么数据丢失?

转载 作者:太空宇宙 更新时间:2023-11-03 17:24:55 24 4
gpt4 key购买 nike

我的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 脚本,该脚本只是将 stdin 写入文件(脚本称为 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) 发送到管道有关。

最佳答案

range()是右侧独有的。

range(0, 33)[0, ..., 32] ,可能是因为这样你就可以 range(0, len(sequence))没有相差一的错误。

32 % 17 == 15 == 0x0f ,字节'\x10'您所期望的一开始就不是列表的一部分。

编辑 1:输出中还缺少零字符 '\x00' 。如果您使用VALUE=$(cat) cat的输出受 shell 处理。

SingleUnix/POSIX 似乎对此事保持沉默。但很明显,您不能拥有 '\0'作为 shell 变量值(或就此而言的名称)的一部分,因为 Unix 环境要求两者都是 C-style zero terminated strings 。我实际上预计 VALUE 的值为空字符串。

编辑2经过一番挖掘,我可以说至少 ash implementation忽略'\0'处理反引号提供的输入。读取输入直到显式跳过 EOF 和空字符。

bash做同样的事情,甚至有一个明确的(即使注释掉)warning与事件相关。

关于python - 当我写入 python 子进程标准输入管道时,为什么数据丢失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32700112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com