PyPerforce: Tutorial: Connecting and running commands

  1. Connecting to a Perforce server
  2. Running commands on a connection
  3. Handling Perforce forms

Connecting to a Perforce server

To connect to a Perforce server you need to use a Connection object.

This is the minimal code required to connect to a Perforce server, assuming that you have the $P4PORT Perforce environment variable set in the calling environment.

#!python
from perforce import Connection
p4 = Connection()
print "Connecting to %s ..." % p4.port
p4.connect()
print "Connected!"
  
print "Disconnecting from server ..."
p4.disconnect()
print "Disconnected!"

Running commands on a connection

Once you have established a connection to a Perforce server you can start running commands using the run() method. The run() method takes the same arguments as the 'p4' command line does and returns a perforce.results.Results object. For example, to get the output of 'p4 info':

#!python
from perforce import Connection
p4 = Connection()
p4.connect()
results = p4.run('info')
p4.disconnect()

# The 'info' command returns a single record
for key, value in results.records[0].iteritems():
  print key, "=", value

To get a list of the files in the depot:

#!python
from perforce import Connection
p4 = Connection()
p4.connect()
results = p4.run('files', '//depot/...')
p4.disconnect()

# The 'files' command returns a record for each file
for record in results.records:
  print "%s#%s" % (record['depotFile'], record['rev'])

Handling Perforce forms

PyPerforce returns Form objects in the results whenever a command is run that outputs a form. You must make sure to specify the '-o' flag for the command when retrieving forms. The returned Form objects behave much like Python dictionaries, accessing fields using index notation, keyed on the field name.

For example:

#!python
from perforce import Connection
p4 = Connection()
p4.connect()
# Retrieve the client form
results = p4.run('client', '-o', 'my-client')
p4.disconnect()

clientForm = results.forms[0]
for fieldName in clientForm:
  print fieldName, "=", clientForm[fieldName]

Index | Home

SourceForge.net Logo