Reputation: 39
I am currently writing a script in Python with the P4Python API which automates the process of checking out a file in Perforce and making some changes to it. I'm currently trying to figure out how to open the file which has been checked out so I can make changes to it but I cannot open it using the "//depot" file path. I'd assume I need to use the system file path (C:/...) but I'm not sure how to proceed.
## 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()
Upvotes: 1
Views: 1441
Reputation: 39
The following bit of code provided me with the local file path:
result = p4.run_fstat("//depot/file/tree/fileToEdit.txt")[0]['clientFile']
print(result)
Using p4.run_fstat("//depot/filename") will provide all the information necessary, the additional "[0]['clientFile']" was to pull the local file path.
Upvotes: 0
Reputation: 71454
Python's open
function operates on local files and has no concept of depot paths, so as you say, you need to use the workspace path. Conveniently, this is returned as part of the p4 edit
output so you can just grab it from there:
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()
Note that this simple script will not work in a case where the p4 edit
command doesn't open the file, e.g. if the file is not synced (in which case maybe your script wants to p4 sync
it), or if the file is already open (in which case maybe you just want to get the local path from p4 opened
and modify it anyway -- or maybe you want to revert the existing changes first, or maybe do nothing at all), or if the file does not exist (in which case maybe you want to p4 add
it instead).
Upvotes: 2