Tuesday, October 29, 2013

P4 Python Beginner Tutorial

If you ever worked in a professional environment then you probably came across Perforce. It has a pretty good client but also gives you different ways of using its functionality in your own applications.

One of them is cmd.exe - it allows you to for instance to submit files/folders or sync to different revisions.

This is actually the way I used perforce so far. Since I love learning new stuff I finally had some time (its been on my to-do list for several years) to check out the Python API and I feel like I just left the 90s.

This will be a little introduction to this API and I will give you a couple of examples of what you can do with it.

First download the python package and make sure the modules end up in a sys.path. If you don't know how to do that, I described this in a previous tutorial.

Load the package

Once you installed everything correct, you can import the P4 and the P4Exception module and instanciate the baseclass called P4().

Examples

So now lets go to town, in this small example we can read what our current workspace is, our computer name and our username. Of course we can also just change those settings and it will update in the perforce client.
So how do we check if we have the latest revision on our workstation? It is as simple as this, all we have to do is compare these two integers.
Note: Usually you have to run p4.connect() at the beginning and p4.disconnect() at the end but if you indent your commands into a with p4.connect() it will automatically close the connection after your commands finished running. Kudos to Adam Pletcher for sharing that.

Another very common example is that we want to sync files. This is also extremely simple. This command lets you either sync a file or a folder, for folders just make sure that the path looks something like this: //depot/myTestfolder/…

For the future

You might recognize a pattern here, in fact all commands look like this:
p4.run_XX. For XX you simply insert whatever the command is for accessing perforce through windows cmd.

So if you used the cmds before, you can easily adapt to the python API.

More on this topic on the official documentation here, it comes with a couple of python of examples. Or you can also just use the full list of all cmds.