gpt4 book ai didi

Python 2.6.4 marshal.load 不接受使用 subprocess.Popen 创建的打开文件对象

转载 作者:行者123 更新时间:2023-11-28 21:30:18 25 4
gpt4 key购买 nike

这是一个非常不幸的情况。 Maya 2011 附带 2.6.4,此代码在其中不起作用:

pipe = subprocess.Popen( 'p4 -G edit C:/somefile.txt', stdout=subprocess.PIPE).stdout

try:
while 1:
record = marshal.load( pipe )
list.append( record )
except EOFError:
pass

各种 2.5 版本都可以使用,最新的 2.6.5 也可以使用,当然不是 Maya 附带的版本!它抛出这个错误:

# Error: TypeError: file <maya console> line 3: marshal.load() arg must be file #

什么是最好的行动方案?

只是为了继续生活,代码被更改为只转储一个文件,这样 marshal.load 就可以加载一个实际的文件。虽然这有效,但它很蹩脚。

Maya 2011 通过 zip 访问 python,因此,作为一个小测试,我压缩了 2.6.5 的 Python26/Lib,并将指向 2.6.4 zip 的 sys.path 条目换成了 2.6.5 zip。虽然我没有对此进行广泛测试,但这似乎有效。我不知道这是比上面那个更好还是更坏的主意。

理想情况下(我认为)我可以在 2.6.4 中做一些事情来完成这项工作,而无需混合 python 版本或一直将临时文件写入磁盘。有什么想法吗?

关于 marshal.loads() 的更新

尝试 marshal.loads(),虽然没有错误,但仍然无法正常工作。我肯定在黑暗中摸索着这些东西。如果文件操作是单独完成的,那么 perforce 的东西慢得无法忍受,必须在一个查询中完成它们。原始代码是这样做的:

files = [a,b,c...n] # Huge list of files
p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
(fi, pipe) = (p.stdin, p.stdout)

# Fill the command up with all the files
for file in files:
fi.write(file + '\n')
fi.close()

# Get all the results
try:
while 1:
record = marshal.load( pipe )
listData.append( record )
except EOFError:
pass

我不知道为什么会这样(在 2.5.x/2.6.5 中)但确实如此; listData 最终作为所有文件结果的列表。我不知道如何使用 marshal.loads() 执行此操作,我只得到第一个结果。此方法几乎一字不差地取自 perforce所以我知道这是做事的方式。很容易想象,我只是不知道如何正确使用子流程和编码。

更新 2 marshal.loads() 完全有效!

经过更多测试后,pipe.read() 提供了所有数据,但它包含一些空字符或其他我不完全理解的内容,因此 marshal.loads() 只会读取第一个条目。在这种特殊情况下,我可以拆分“{”上的数据并收集数据。

listData = []
results = pipe.read().split("{")
# Skip the first entry since it's empty
for result in results[1:]:
listData.append( marshal.loads( "{" + result) )

感谢 Cristian 为我指明了正确的方向,希望任何使用 perforce 升级到 Maya 2011 的人都能让事情变得更顺利。

最佳答案

使用 -G 选项解码 p4 的输出时遇到同样的问题。 marshal.loads(str) 仅读取第一条记录,marshal.load(StringIO(str)) 失败并显示“marshal.load() arg 必须是文件”。我没有使用拆分建议,而是使用了临时文件解决方法:

import subprocess, marshal, tempfile

tempf = tempfile.TemporaryFile()
subprocess.Popen(cmd, stdout=tempf).communicate()
tempf.seek(0)
try:
while 1:
record = marshal.load(tempf)
listData.append( record )
except EOFError:
pass
tempf.close()

请注意,python 会在您关闭临时文件后立即为您删除它。

关于Python 2.6.4 marshal.load 不接受使用 subprocess.Popen 创建的打开文件对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3249822/

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