Another cool thing about perforce: Python

Friday 6 February 2004

I like Perforce a lot. It’s lean and clean. I’ve always liked their approach of making the command line fully functional and then building on it as a way of providing multiple interfaces and platforms. But here’s a twist on that idea that I just discovered: every command can take a -G switch which makes the output be marshalled Python objects, to aid in scripting.

To try it out, use this script:

# p4py.py: show off Perforce Python-marshalled output.
import marshal, os, pprint, sys

P4 = '"c:/program files/perforce/p4"'
fP4 = os.popen(P4 + ' -G ' + ' '.join(sys.argv[1:]), 'rb')

while 1:
    try:
        d = marshal.load(fP4)
        pprint.pprint(d)
    except EOFError:
        break

This script will accept any p4 command line and show the output as Python objects:

$ p4py describe 14262
{'action0': 'edit',
 'action1': 'edit',
 'change': '14262',
 'client': 'NedLaptop',
 'code': 'stat',
 'depotFile0': '//depot/main/dev/myproject/MyClass.h',
 'depotFile1': '//depot/main/dev/myproject/MyClass.cpp',
 'desc': 'A week ago I could not even spell programmer, and now I are one!\n',
 'rev0': '6',
 'rev1': '4',
 'status': 'submitted',
 'time': '1075862325',
 'type0': 'ktext',
 'type1': 'ktext',
 'user': 'ned'}

Granted, a genuine API would be even better, and the data structure presented here is a little odd (why the parallel dict keys to represent more than one changed file?), but this is a lot better than screen scraping.

Comments

[gravatar]
Trent Mick 5:02 PM on 12 Feb 2004

I have a Python tool (px) and lib (p4lib.py) that lightly wraps the 'p4' command line to extend a few commands and add a few. It uses this "-G" option for some of the command handling. 'px' also provides a -g option to do the unmarshalling for you so:

$ px -g describe 91118
{'action0': 'edit',
'change': '91118',
'client': 'trentm-planer',
'code': 'stat',
'depotFile0': '//depot/main/Apps/Komodo-devel/src/lint/koPythonLinter.py',
'desc': 'Little buglet fix from BrianQ.\n',
'rev0': '12',
'status': 'submitted',
'time': '1076521108',
'type0': 'text',
'user': 'trentm'}

Anyway, yes, Perforce's -G is pretty cool.

Add a comment:

Ignore this:
Leave this empty:
Name is required. Either email or web are required. Email won't be displayed and I won't spam you. Your web site won't be indexed by search engines.
Don't put anything here:
Leave this empty:
URLs auto-link and some tags are allowed: <a><b><i><p><br><pre>.