多年前的这个问题符合我的要求:
但有没有办法使用子进程模块执行此操作?(据我所知是首选方式)
我查看了stackoverflow,python文档,以及许多谷歌搜索试图找到一种方法来使用stdin将所需的输入发送到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
Run Code Online (Sandbox Code Playgroud)
正如我在评论中提到的,使用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
Run Code Online (Sandbox Code Playgroud)