【问题标题】:Python - Subprocess with STDIN and STDOUTPython - 带有 STDIN 和 STDOUT 的子进程
【发布时间】:2021-06-02 14:48:37
【问题描述】:

我想将一个字节对象从文件 A.py 传递给 B.py,在 B.py 中它递增 1,然后传回。目前我有以下代码,每当我运行python A.py 时,程序不会打印任何内容。虽然我不确定,但我觉得问题出在文件 B.py 中。

A.py

import subprocess
import struct

door = subprocess.Popen(['python','B.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
door.stdin.write(struct.pack(">B", 0))
door.stdin.flush()
print(struct.unpack(">B", door.stdout.read()))

B.py

import sys
import struct

my_input = sys.stdin.buffer.read()
nbr = struct.unpack(">B", my_input)
sys.stdout.buffer.write(struct.pack(">B",nbr+1))
sys.stdout.buffer.flush()

【问题讨论】:

    标签: python subprocess stdout stdin


    【解决方案1】:

    B.py 中,您没有指定要读取多少字节。它默认读取直到它得到 EOF,直到 A.py 关闭管道才会发生。

    所以要么在写入后关闭A.py 中的管道(将door.stdin.flush() 替换为close(door.stdin),或者让B.py 只读取它需要的字节数。

    my_input = sys.stdin.buffer.read(struct.calcsize(">B"))
    

    【讨论】:

    • 只有当 A.py 关闭到 B.py 的管道时,有没有办法礼貌地退出 B.py?
    • B.py 可以再次调用sys.stdin.buffer.read() 等待EOF。
    猜你喜欢
    • 2017-04-16
    • 2013-05-16
    • 2014-02-14
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    • 1970-01-01
    • 2012-05-20
    • 2022-11-03
    相关资源
    最近更新 更多