How do I check out a file from perforce in python?

Matt Price picture Matt Price · Oct 8, 2008 · Viewed 17.5k times · Source

I would like to write some scripts in python that do some automated changes to source code. If the script determines it needs to change the file I would like to first check it out of perforce. I don't care about checking in because I will always want to build and test first.

Answer

Troy J. Farrell picture Troy J. Farrell · Oct 8, 2008

Perforce has Python wrappers around their C/C++ tools, available in binary form for Windows, and source for other platforms:

http://www.perforce.com/perforce/loadsupp.html#api

You will find their documentation of the scripting API to be helpful:

http://www.perforce.com/perforce/doc.current/manuals/p4script/p4script.pdf

Use of the Python API is quite similar to the command-line client:

PythonWin 2.5.1 (r251:54863, May  1 2007, 17:47:05) [MSC v.1310 32 bit (Intel)] on win32.
Portions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin' for further copyright information.
>>> import P4
>>> p4 = P4.P4()
>>> p4.connect() # connect to the default server, with the default clientspec
>>> desc = {"Description": "My new changelist description",
...         "Change": "new"
...         }
>>> p4.input = desc
>>> p4.run("changelist", "-i")
['Change 2579505 created.']
>>> 

I'll verify it from the command line:

P:\>p4 changelist -o 2579505
# A Perforce Change Specification.
#
#  Change:      The change number. 'new' on a new changelist.
#  Date:        The date this specification was last modified.
#  Client:      The client on which the changelist was created.  Read-only.
#  User:        The user who created the changelist.
#  Status:      Either 'pending' or 'submitted'. Read-only.
#  Description: Comments about the changelist.  Required.
#  Jobs:        What opened jobs are to be closed by this changelist.
#               You may delete jobs from this list.  (New changelists only.)
#  Files:       What opened files from the default changelist are to be added
#               to this changelist.  You may delete files from this list.
#               (New changelists only.)

Change: 2579505

Date:   2008/10/08 13:57:02

Client: MYCOMPUTER-DT

User:   myusername

Status: pending

Description:
        My new changelist description