0

多年前的这个问题满足了我的需要:

如何在 python 中从 perforce 中签出文件?

但是有没有办法使用 subprocess 模块来做到这一点?(我理解这是首选方式)

我查看了 stackoverflow、python 文档以及许多谷歌搜索,试图找到一种方法来使用标准输入将所需的输入发送到 p4 进程,但我没有成功。我已经能够在捕获子进程命令的输出方面找到很多东西,但无法理解输入命令。

一般来说,我对 python 很陌生,所以我可能会遗漏一些明显的东西,但我不知道在这种情况下我不知道什么。

这是我到目前为止提出的代码:

descr = "this is a test description"
tempIn = tempfile.TemporaryFile()
tempOut = tempfile.TemporaryFile()
p = subprocess.Popen(["p4","change","-i"],stdout=tempOut, stdin=tempIn)
tempIn.write("change: New\n")
tempIn.write("description: " + descr)
tempIn.close()

(out, err) = p.communicate()
print out
4

2 回答 2

5

正如我在评论中提到的,使用 Perforce Python API

关于您的代码:

tempfile.TemporaryFile()通常不适合创建文件然后将内容传递给其他东西。临时文件一关闭就会自动删除。通常,您需要先关闭文件进行写入,然后才能重新打开文件进行读取,这会造成 catch-22 情况。(您可以使用 来解决这个问题tempfile.NamedTemporaryFile(delete=False),但对于这种情况来说,这仍然过于迂回。)

要使用communicate()您需要传递 subprocess.PIPE

descr = "this is a test description"
changespec = "change: New\ndescription: " + descr

p = subprocess.Popen(["p4","change","-i"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

(out, err) = p.communicate(changespec)
print out
于 2013-01-11T21:39:30.370 回答
0

如果stdout不是无限的,则使用@Jon-Eric 的答案,否则替换p.communicate()rc = p.wait(); tempOut.seek(0); chunk = tempOut.read(chunk_size) ....

于 2013-01-11T22:16:03.207 回答