在Windows上将二进制文件从Python3传递到Python2

2024-04-20 00:42:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我们有两个python脚本,它们需要通过stdin/out(在Windows上)进行通信。遗憾的是,它们必须在不同的Python版本中。这些代码段包括:

源代码(Python 3):

sys.stderr.write("LEN1: %s\n" % len(source_file.read()))
subprocess.check_call(["C:\\python2.exe", "-u", "-c",
"""
import foo
foo.to_json()
"""], stdin=source_file, stdout=json_file, stderr=sys.stderr, env=os.environ)

目标(Python 2):

def to_json():
  import msvcrt
  msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
  input_message = sys.stdin.read()
  sys.stderr.write("LEN2: %s\n" % len(input_message))

当我执行脚本时,我得到:

LEN2: 0
LEN1: 37165

似乎我做错了什么,但我真的不知道到底是什么。有谁能帮我调试一下,我哪里出错了。你知道吗


Tags: toimport脚本jsonsourcereadlenfoo
1条回答
网友
1楼 · 发布于 2024-04-20 00:42:04

在确定文件长度的第一个source_file.read()之后,文件指针位于文件的末尾。当您将流传递给check_call()时,您已经耗尽了它,进一步读取将产生空字符串。这可以通过两种方式解决:

在计算文件长度之前先把它读入内存。你知道吗

B.在check_call()之前,用source_file.seek(0)将file对象倒带到文件的开头。你知道吗

相关问题 更多 >