问题描述
我目前正在使用P4Python API用Python编写脚本,该脚本可以自动执行在Perforce中检出文件并对文件进行一些更改的过程。我目前正在尝试找出如何打开已签出的文件,以便可以对其进行更改,但无法使用“ // depot”文件路径打开它。我以为我需要使用系统文件路径(C:/ ...),但不确定如何继续。
## Connect to P4 server
p4.connect()
## Checkout file to default changelist
p4.run_edit("//depot/file/tree/filetoEdit.txt")
f1 = "//depot/file/tree/filetoEdit.txt" ## This file path does not work
with open(f1,'w') as file1:
file1.write("THIS IS A TEST")
## disconnect from P4 server
p4.disconnect()
解决方法
Python的open
函数在本地文件上运行,并且没有库路径的概念,因此,正如您所说,您需要使用工作空间路径。方便地,这是作为p4 edit
输出的一部分返回的,因此您可以从那里获取它:
from P4 import P4
p4 = P4()
## Connect to P4 server
p4.connect()
## Checkout file to default changelist
local_paths = [
result['clientFile']
for result in p4.run_edit("//depot/file/tree/fileToEdit.txt")
]
for path in local_paths:
with open(path,'w') as f:
f.write("THIS IS A TEST")
## Disconnect from P4 server
p4.disconnect()
请注意,在p4 edit
命令无法打开文件的情况下(例如,如果文件未同步(在这种情况下,您的脚本可能想要p4 sync
),或者文件已经打开(在这种情况下,您只想从p4 opened
获取本地路径,然后修改它-也许您想先还原现有的更改,或者什么都不做),或者如果文件不存在(在这种情况下,您可能想p4 add
对其进行修改)。>
以下代码为我提供了本地文件路径:
result = p4.run_fstat("//depot/file/tree/fileToEdit.txt")[0]['clientFile']
print(result)
使用p4.run_fstat(“ // depot / filename”)将提供所有必要的信息,另外的[[0] ['clientFile']“用于提取本地文件路径。