P4Python provides an object-oriented interface to Perforce that is intended to be intuitive for Python programmers. Data is loaded and returned in Python arrays and dictionaries. Each P4 object represents a connection to the Perforce Server.
When instantiated, the P4 instance is set up with the default environment settings just as the command line client p4, that is, using environment variables, the registry or user preferences (on Windows and OS X) and, if defined, the
P4CONFIG file. The settings can be checked and changed before the connection to the server is established with the
connect() method. After your script connects, it can send multiple commands to the Perforce Server with the same P4 instance. After the script is finished, it should disconnect from the Server by calling the
disconnect() method.
The following example illustrates the basic structure of a P4Python script. The example establishes a connection, issues a command, and tests for errors resulting from the command.
from P4 import P4,P4Exception # Import the module p4 = P4() # Create the P4 instance p4.port = "1666" p4.user = "fred" p4.client = "fred-ws" # Set some environment variables try: # Catch exceptions with try/except p4.connect() # Connect to the Perforce Server info = p4.run("info") # Run "p4 info" (returns a dict) for key in info[0]: # and display all key-value pairs print key, "=", info[0][key] p4.run("edit", "file.txt") # Run "p4 edit file.txt" p4.disconnect() # Disconnect from the Server except P4Exception: for e in p4.errors: # Display errors print e
|
try: p4.connect() # Convert client spec into a Python dictionary client = p4.fetch_client("-t", template) client._root = client_root p4.save_client(client) p4.run_sync()
except P4Exception: # If any errors occur, we'll jump in here. Just log them # and raise the exception up to the higher level
|
p4 = P4()p4.connect() change = p4.fetch_change()
|
p4 = P4()p4.user = "Sven" p4.password = "my_password" p4.connect() p4.run_login() opened = p4.run_opened()
|
Scripts written with P4Python use any existing P4TRUST file present in their operating environment (by default,
.p4trust in the home directory of the user that runs the script).
If the fingerprint returned by the server fails to match the one installed in the P4TRUST file associated with the script's run-time environment, your script will (and should!) fail to connect to the server.
p4 = P4()p4.user = "Sven" p4.password = "MyOldPassword" p4.connect()
|
Timestamp information in P4Python is normally represented as seconds since Epoch (with the exception of
P4.Revision). To convert this data to a more useful format, use the following procedure:
As of P4Python 2012.3, comments in specs are preserved in the parse_spectype() and
format_spectype() methods. This behavior can be circumvented by using
parse_spec('spectype', spec) and
format_spec('spectype', spec) instead of
parse_spectype(spec)and
parse_spectype(spec). For example:
The following table lists attributes of the class P4 in P4Python. The attributes are readable and writable unless indicated otherwise. The attributes can be strings, objects, or integers.
|
|
|
|
|
|
|
P4CLIENT, the name of the client workspace to use.
|
|
|
|
Encoding to use when receiving strings from a non-Unicode server. If unset, use UTF8. Can be set to a legal Python encoding, or to raw to receive Python bytes instead of Unicode strings. Requires Python 3.
|
|
|
|
|
|
|
|
P4HOST, the name of the host used
|
|
|
|
|
|
|
|
|
|
An array of P4.Message objects, one for each message sent by the server.
|
|
|
|
P4PASSWD, the password used.
|
|
P4PORT, the port used for the connection
|
|
|
|
|
|
|
|
|
|
|
|
To disable streams support, set the value to 0 or False. By default, streams output is enabled for servers at 2011.1 or higher.
|
|
To disable tagged output for the following commands, set the value to 0 or False. By default, tagged output is enabled.
|
|
To enable performance tracking for the current connection, set the value to 1 or True. By default, server tracking is disabled.
|
|
If performance tracking is enabled, returns an array containing performance tracking information received during execution of the last command
|
|
P4TICKETS, the ticket file location used
|
|
P4USER, the user under which the connection is run
|
|
|
|
|
The following table lists all public methods of the class P4. Many methods are wrappers around
P4.run(), which sends a command to the Perforce Server. Such methods are provided for your convenience.
Exception class. Instances of this class are raised when errors and/or (depending on the exception_level setting) warnings are returned by the server. The exception contains the errors in the form of a string.
P4Exception is a subclass of the standard Python Exception class.
Container class returned by P4.run_filelog(). Contains the name of the depot file and a list of
P4.Revision objects.
Handler class that provides access to streaming output from the server; set P4.handler to an instance of a subclass of
P4.OutputHandler to enable callbacks:
This module provides an object-oriented interface to the Perforce version management system. Data is returned in Python arrays and dictionaries (hashes) and input can also be supplied in these formats.
Each P4 object represents a connection to the Perforce Server, and multiple commands may be executed (serially) over a single connection (which of itself can result in substantially improved performance if executing long sequences of Perforce commands).
Contains the API compatibility level desired. This is useful when writing scripts using Perforce commands that do not yet support tagged output. In these cases, upgrading to a later server that supports tagged output for the commands in question can break your script. Using this method allows you to lock your script to the output format of an older Perforce release and facilitate seamless upgrades. Must be called before calling
P4.connect().
from P4 import P4p4 = P4() p4.api_level = 67 # Lock to 2010.1 format p4.connect() ... p4.disconnect
|
Contains the character set to use when connect to a Unicode enabled server. Do not use when working with non-Unicode-enabled servers. By default, the character set is the value of the
P4CHARSET environment variable. If the character set is invalid, this method raises a
P4Exception.
from P4 import P4p4 = P4() p4.client = "www" p4.charset = "iso8859-1" p4.connect() p4.run_sync() p4.disconnect()
|
Contains the name of your client workspace. By default, this is the value of the P4CLIENT taken from any
P4CONFIG file present, or from the environment according to the normal Perforce conventions.
Contains the current working directly. Can be called prior to executing any Perforce command. Sometimes necessary if your script executes a
chdir() as part of its processing.
When decoding strings from a non-Unicode server, strings are assumed to be encoded in UTF8. To use another encoding, set
p4.encoding to a legal Python encoding, or
raw to receive Python bytes instead of a Unicode string. Available only when compiled with Python 3.
try: p4.connect() p4.exception_level = 1 # ignore "File(s) up-to-date" files = p4.run_sync()
|
from P4 import P4p4 = P4() p4.exception_level = 1 p4.connect() # P4Exception on failure p4.run_sync() # File(s) up-to-date is a warning - no exception raised p4.disconnect()
|
Contains the name of the current host. It defaults to the value of P4HOST taken from any
P4CONFIG file present, or from the environment as per the usual Perforce convention. Must be called before connecting to the Perforce server.
from P4 import P4p4 = P4() p4.host = "workstation123.perforce.com" p4.connect() ... p4.disconnect()
|
Set this attribute prior to running a command that requires input from the user. When the command requests input, the specified data is supplied to the command. Typically, commands of the form
p4 cmd -i are invoked using the
P4.save_spectype methods, which retrieve the value from
p4.input internally; there is no need to set
p4.input when using the
P4.save_spectype shortcuts.
You may pass a string, a hash, or (for commands that take multiple inputs from the user) an array of strings or hashes. If you pass an array, note that the first element of the array will be popped each time Perforce asks the user for input.
from P4 import P4p4 = P4() p4.connect() change = p4.run_change( "-o" )[0] change[ "Description" ] = "Autosubmitted changelist" p4.input = change p4.run_submit( "-i" ) p4.disconnect()
|
The iterate_spectype methods are shortcut methods that allow you to quickly iterate through clients, labels, branches, etc. Valid
spectypes are
clients,
labels,
branches,
changes,
streams,
jobs,
users,
groups,
depots and
servers. Valid arguments are any arguments that would be valid for the corresponding
run_spectype command.
Limit the amount of time (in milliseconds) spent during data scans to prevent the server from locking tables for too long. Commands that take longer than the limit will be aborted. The limit remains in force until you disable it by setting it to zero. See
p4 help maxlocktime for information on the commands that support this limit.
Limit the number of results Perforce permits for subsequent commands. Commands that produce more than this number of results will be aborted. The limit remains in force until you disable it by setting it to zero. See
p4 help maxresults for information on the commands that support this limit.
Limit the number of database records Perforce scans for subsequent commands. Commands that attempt to scan more than this number of records will be aborted. The limit remains in force until you disable it by setting it to zero. See
p4 help maxscanrows for information on the commands that support this limit.
Returns a list of P4.Message objects, one for each message (info, warning or error) sent by the server.
Contains the name of the current P4CONFIG file, if any. This attribute cannot be set.
Contains your Perforce password or login ticket. If not used, takes the value of P4PASSWD from any
P4CONFIG file in effect, or from the environment according to the normal Perforce conventions.
This password is also used if you later call p4.run_login() to log in using the 2003.2 and later ticket system. After running
p4.run_login(), the attribute contains the ticket the allocated by the server.
Contains the host and port of the Perforce server to which you want to connect. It defaults to the value of
P4PORT in any
P4CONFIG file in effect, and then to the value of
P4PORT taken from the environment.
Returns the current Perforce server level. Each iteration of the Perforce Server is given a level number. As part of the initial communication this value is passed between the client application and the Perforce Server. This value is used to determine the communication that the Perforce Server will understand. All subsequent requests can therefore be tailored to meet the requirements of this Server level.
If 1 or True, p4.streams enables support for streams. By default, streams support is enabled at 2011.1 or higher (
api_level >= 70). Raises a
P4Exception if you attempt to enable streams on a pre-2011.1 server. You can enable or disable support for streams both before and after connecting to the server..
If 1 or True, p4.tagged enables tagged output. By default, tagged output is on.
If set to 1 or True, p4.track indicates that server performance tracking is enabled for this connection. By default, performance tracking is disabled.
If performance tracking is enabled with p4.track, returns an array containing the performance data received during execution of the last command.
Contains the Perforce username. It defaults to the value of P4USER taken from any
P4CONFIG file present, or from the environment as per the usual Perforce convention.
try: p4.connect() p4.exception_level = 2 # File(s) up-to-date is a warning files = p4.run_sync()
|
Construct a new P4 object. For example:
The read-only string attributes PATCHLEVEL and
OS are also available to test an installation of P4Python without having to parse the output of
P4.identify().
If applicable, P4.identify() also reports the version of the OpenSSL library used for building the underlying Perforce C++ API with which P4Python was built.
In the context of a with statement, temporarily set the exception level for a block. For example:
from P4 import P4p4 = P4() p4.connect() with p4.at_exception_level(P4.RAISE_ERRORS): # no exceptions for warnings p4.run_sync("//depot/main/...")
|
If the connection is successfully established, returns None. If the connection fails and
exception_level is 0, returns False, otherwise raises a
P4Exception. If already connected, prints a message.
P4.connect returns a context management object that is usable with a with statement within a block; after the block is finished, the connection is automatically disconnected:
import P4p4 = P4.P4() with p4.connect(): # block in context of connection ...
|
The delete_spectype methods are shortcut methods that allow you to delete the definitions of clients, labels, branches, etc. These methods are equivalent to:
The following code uses delete_client to delete client workspaces that have not been accessed in more than 365 days:
try: p4.connect() for client in p4.run_clients(): atime = datetime.utcfromtimestamp( int( client[ "Access" ] ) ) # If the client has not been accessed for a year, delete it if ( atime + timedelta(365) ) < now : p4.delete_client( '-f', client[ "client" ] )
|
Get the value of a Perforce environment variable, taking into account P4CONFIG files and (on Windows or OS X) the registry or user preferences.
The fetch_spectype methods are shortcuts for running
p4.run("spectype", "-o").pop(0). For example:
label = p4.fetch_label(labelname) change = p4.fetch_change(changeno) clientspec = p4.fetch_client(clientname)
|
label = p4.run("label", "-o", labelname)[0] change = p4.run("change", "-o", changeno)[0] clientspec = p4.run("client", "-o", clientname)[0]
|
Converts the fields in the dict containing the elements of a Perforce form (spec) into the string representation familiar to users. The first argument is the type of spec to format: for example, client, branch, label, and so on. The second argument is the hash to parse.
There are shortcuts available for this method. You can use p4.format_spectype( dict ) instead of
p4.format_spec( spectype, dict ), where
spectype is the name of a Perforce spec, such as client, label, etc.
The format_spectype methods are shortcut methods that allow you to quickly fetch the definitions of clients, labels, branches, etc. They're equivalent to:
Parses a Perforce form (spec) in text form into a Python dict using the spec definition obtained from the server. The first argument is the type of spec to parse:
client,
branch,
label, and so on. The second argument is the string buffer to parse.
where spectype is one of
client,
branch,
label, and so on.
This is equivalent to parse_spec( spectype, string ).
For example, parse_job(myJob) converts the String representation of a job spec into a Spec object.
To parse a spec, P4 needs to have the spec available. When not connected to the Perforce Server, P4 assumes the default format for the spec, which is hardcoded. This assumption can fail for jobs if the Server's jobspec has been modified. In this case, your script can load a job from the Server first with the command
fetch_job('somename'), andP4 will cache and use the spec format in subsequent
parse_job() calls.
Base interface to all the run methods in this API. Runs the specified Perforce command with the arguments supplied. Arguments may be in any form as long as they can be converted to strings by
str().
The p4.run() method returns a list of results whether the command succeeds or fails; the list may, however, be empty. Whether the elements of the array are strings or dictionaries depends on
In the event of errors or warnings, and depending on the exception level in force at the time,
run() raises a
P4Exception. If the current exception level is below the threshold for the error/warning,
run() returns the output as normal and the caller must explicitly review
p4.errors and
p4.warnings to check for errors or warnings.
from P4 import P4p4 = P4() p4.connect() spec = p4.run( "client", "-o" )[0] p4.disconnect()
|
Shortcuts are available for p4.run. For example,
p4.run_command( args ) is equivalent to
p4.run( "command", args )
from P4 import P4p4 = P4() p4.connect() clientspec = p4.run_client( "-o" ).pop(0) clientspec[ "Description" ] = "Build client" p4.input = clientspec p4.run_client( "-i" ) p4.disconnect()
|
from P4 import P4p4 = P4() p4.connect() clientspec = p4.fetch_client() clientspec[ "Description" ] = "Build client" p4.save_client( clientspec ) p4.disconnect()
|
As the commands associated with fetch_spectype typically return only one item, these methods do not return an array, but instead return the first result element.
Shorthand for p4.run("cmd", arguments... )
Runs a p4 filelog on the
fileSpec provided and returns an array of
P4.DepotFile results (when executed in tagged mode), or an array of strings when executed in nontagged mode. By default, the raw output of
p4 filelog is tagged; this method restructures the output into a more user-friendly (and object-oriented) form.
try: p4.connect() for r in p4.run_filelog( "index.html" )[0].revisions: for i in r.integrations: # Do something
|
Runs p4_login using a password or ticket set by the user.
try: p4.connect() p4.run_password( "myoldpass", "mynewpass" )
|
Run a p4 resolve command. Interactive resolves require the
resolver parameter to be an object of a class derived from
P4.Resolver. In these cases, the
resolve method of this class is called to handle the resolve. For example:
class MyResolver(P4.Resolver): def resolve(self, mergeData): if not mergeData.merge_hint == "e": return mergeData.merge_hint else: return "s" # skip the resolve, there is a conflict
|
In non-interactive resolves, no P4.Resolver object is required. For example:
p4.run_tickets() returns an array of lists of the form (
p4port,
user,
ticket) based on the contents of the local tickets file.
The save_spectype methods are shortcut methods that allow you to quickly update the definitions of clients, labels, branches, etc. They are equivalent to:
try: p4.connect() client = p4.fetch_client() client[ "Owner" ] = p4.user p4.save_client( client )
|
On Windows or OS X, set a variable in the registry or user preferences. To unset a variable, pass an empty string as the second argument. On other platforms, an exception is raised.
In the context of a with statement, enable or disable tagged behavior for the duration of a block. For example:
from P4 import P4p4 = P4() p4.connect() with p4.while_tagged(False): # tagged output disabled for this block print p4.run_info()
|
Instances of this class are raised when P4 encounters an error or a warning from the server. The exception contains the errors in the form of a string.
P4Exception is a shallow subclass of the standard Python Exception class.
Utility class providing easy access to the attributes of a file in a Perforce depot. Each P4.DepotFile object contains summary information about the file and a list of revisions (
P4.Revision objects) of that file. Currently, only the
P4.run_filelog method returns a list of
P4.DepotFile objects.
Returns a list of P4.Revision objects, one for each revision of the depot file.
Returns the description of the change which created this revision. Note that only the first 31 characters are returned unless you use
p4 filelog -L for the first 250 characters, or
p4 filelog -l for the full text.
Returns the list of P4.Integration objects for this revision.
The P4.Map class allows users to create and work with Perforce mappings, without requiring a connection to a Perforce server.
Join two P4.Map objects and create a third.
May be called with one or two arguments. If called with one argument, the string is assumed to be a string containing either a half-map, or a string containing both halves of the mapping. In this form, mappings with embedded spaces must be quoted. If called with two arguments, each argument is assumed to be half of the mapping, and quotes are optional.
Translate a string through a map, and return the result. If the optional second argument is 1, translate forward, and if it is 0, translate in the reverse direction. By default, translation is in the forward direction.
Return a new P4.Map object with the left and right sides of the mapping swapped. The original object is unchanged.
Returns the path to the merge result. This is typically a path to a temporary file on your local machine in which the contents of the automatic merge performed by the server have been loaded.
If the environment variable P4MERGE is defined,
run_merge() invokes the specified program and returns a boolean based on the return value of that program.
P4.Message objects contain error or other diagnostic messages from the Perforce Server; they are returned in
P4.messages.
Script writers can test the severity of the messages in order to determine if the server message consisted of command output (
E_INFO), warnings, (
E_WARN), or errors (
E_FAILED/
E_FATAL).
The P4.OutputHandler class is a handler class that provides access to streaming output from the server. After defining the output handler, set
p4.handler to an instance of a subclass of
P4.OutputHandler, use
p4.using_handler(MyHandler()), or pass the handler as a named parameter for one statement only.
By default, P4.OutputHandler returns
REPORT for all output methods. The different return options are:
P4.Progress is a handler class that provides access to progress indicators from the server. After defining the progress class, set
p4.progress to an instance of a subclass of
P4.Progress, use
p4.using_progress(MyProgress()), or pass the progress indicator as a named parameter for one statement only.
P4.Resolver is a class for handling resolves in Perforce. It is intended to be subclassed, and for subclasses to override the
resolve() method. When
P4.run_resolve() is called with a
P4.Resolver object, it calls the
resolve() method of the object once for each scheduled resolve.
By default, all automatic merges are accepted, and all merges with conflicts are skipped. The
resolve method is called with a single parameter, which is a reference to a
P4.MergeData object.
Only valid field names may be set in a P4.Spec object. Only the field name is validated, not the content. Attributes provide easy access to the fields.
Contains an array containing the names of fields that are valid in this spec object. This does not imply that values for all of these fields are actually set in this object, merely that you may choose to set values for any of these fields if you want to.
Constructs a new P4.Spec object given an array of valid fieldnames.
Copyright 2008-2014 Perforce Software.