### Run P4 Command with Arguments Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.installation.html Example of running a P4 command using the P4Python API, noting that arguments and values must be concatenated without spaces. ```python change = p4.run_changes("-u_username_", "-m1")[0] ``` -------------------------------- ### Install and Verify P4Python via pip Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.installation.html Commands to upgrade pip, install the P4Python package, and verify the installation by importing the P4 module in Python. ```bash python -m pip install --upgrade pip pip install p4python python -c "import P4; print('P4Python installed!')" ``` -------------------------------- ### Configure Perforce APT Repository for Ubuntu Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.installation.html Commands to add the Perforce repository to the sources list and import the signing key for various Ubuntu versions. ```bash # Ubuntu 20.04 echo "deb http://package.perforce.com/apt/ubuntu/ focal release" | sudo tee /etc/apt/sources.list.d/perforce.list # Ubuntu 22.04 echo "deb http://package.perforce.com/apt/ubuntu/ jammy release" | sudo tee /etc/apt/sources.list.d/perforce.list # Ubuntu 24.04 echo "deb http://package.perforce.com/apt/ubuntu/ noble release" | sudo tee /etc/apt/sources.list.d/perforce.list # Import key and update wget -qO - https://package.perforce.com/perforce.pubkey | sudo apt-key add - sudo apt-get update ``` -------------------------------- ### Execute P4 Python Test Script Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.installation.html Command line instructions to navigate to the script directory and execute the verification script using the Python interpreter. ```bash cd c:\\p4python python test_p4.py ``` -------------------------------- ### Install P4 API for Python via Package Manager Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.installation.html Commands to install the P4 API for Python meta-package on Debian-based and RHEL-based Linux distributions. ```bash sudo apt install perforce-p4python3 sudo yum install perforce-p4python3 ``` -------------------------------- ### Verify P4 API for Python Connection Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.installation.html A Python script to test connectivity to a Perforce server by initializing a P4 object, connecting, and handling potential exceptions. ```python from P4 import P4, P4Exception # Configure Perforce p4 = P4() p4.port = "perforce:1666" p4.user = "user.name" # update with your username p4.client = "workspace" # update with your workspace try: p4.connect() print("Connected to Perforce server:", p4.port) print("Current client workspace:", p4.client) except P4Exception as e: print("Could not connect. Error:", e) finally: p4.disconnect() ``` -------------------------------- ### Configure Perforce YUM Repository for RHEL/Rocky Linux Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.installation.html Configuration content for the Perforce repository file and the command to import the GPG signing key for RHEL/Rocky Linux systems. ```ini [Perforce] name=Perforce baseurl=http://package.perforce.com/yum/rhel/9/x86_64/ enabled=1 gpgcheck=1 ``` ```bash sudo rpm --import https://package.perforce.com/perforce.pubkey ``` -------------------------------- ### Execute P4 Commands using Shortcut Syntax Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html Provides shortcut methods for executing P4 commands, simplifying the syntax. For example, `p4.run__command_(_args_)` is equivalent to `p4.run( "_command_", _args_ )`. ```python from P4 import P4 p4 = P4() p4.connect() clientspec = p4.run_client( "-o" )[0] clientspec[ "Description" ] = "Build client" p4.input = clientspec p4.run_client( "-i" ) p4.disconnect() ``` -------------------------------- ### P4 Python: Submit a Changelist with Specific Files Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.programming.html This example demonstrates how to create and submit a changelist using the P4 API for Python. It fetches a new changelist, sets its description and the list of files to be included, and then submits the changelist to the P4 Server. ```python from P4 import P4 p4 = P4() p4.connect() change = p4.fetch_change() myfiles = ['//depot/some/path/file1.c', '//depot/some/path/file1.h'] change._description = "My changelist\nSubmitted from P4Python\n" change._files = myfiles p4.run_submit( change ) ``` -------------------------------- ### Handle P4Python Errors and Warnings Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html Shows how to retrieve error messages after command execution using `p4.errors`. This example also demonstrates how to catch `P4Exception` and iterate through the errors. ```python from P4 import P4, P4Exception p4 = P4() try: p4.connect() # generate an error ("syn" instead of "sync"): # Unknown command. Try 'p4 help' for info. p4.run_syn() except P4Exception: for e in p4.errors: print(e) finally: p4.disconnect() ``` -------------------------------- ### p4.prog Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html Sets or gets the program name reported to P4 Server administrators. Defaults to 'unnamed p4-python script'. ```APIDOC ## p4.prog ### Description Contains the name of the program, as reported to P4 Server system administrators running `**p4 monitor show -e**`. The default is `unnamed p4-python script`. ### Method SET/GET ### Endpoint N/A (Attribute of P4 object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from P4 import P4 p4 = P4() p4.prog = "sync-script" print(p4.prog) p4.connect() # ... operations ... p4.disconnect() ``` ### Response #### Success Response (200) N/A (Attribute access) #### Response Example ``` "sync-script" ``` ``` -------------------------------- ### Identify P4 API Version Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html Retrieves the version information for the installed P4 API for Python. ```python import P4 print(P4.identify()) ``` -------------------------------- ### p4.port Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html Sets or gets the host and port for connecting to the P4 Server. Defaults to P4PORT from P4CONFIG or environment variables. ```APIDOC ## p4.port ### Description Contains the host and port of the P4 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. ### Method SET/GET ### Endpoint N/A (Attribute of P4 object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from P4 import P4 p4 = P4() p4.port = "localhost:1666" p4.connect() # ... operations ... p4.disconnect() ``` ### Response #### Success Response (200) N/A (Attribute access) #### Response Example ``` "localhost:1666" ``` ``` -------------------------------- ### Customize P4Python PyKeepAlive isAlive() Method Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4_pykeepalive.html Demonstrates how to subclass P4.PyKeepAlive and override the isAlive() method to implement custom logic for terminating P4 commands. This example shows interrupting a 'changes' command after three checks. ```python import P4 # subclass KeepAlive to implement a customized IsAlive function. class MyKeepAlive(P4.PyKeepAlive): def __init__(self): P4.PyKeepAlive.__init__(self) self.counter = 0 # Set up the interrupt callback. After being called 3 times, # interrupt 3 times, interrupt the current server operation. def isAlive(self): self.counter += 1 if self.counter > 3: return 0 return 1 # Now test the callback p4 = P4.P4() p4.connect() kaObj=MyKeepAlive() p4.setbreak(kaObj) # SetBreak must happen after the p4.connect() p4.run("changes") p4.disconnect() ``` -------------------------------- ### Get File Log with p4.run_filelog() Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html Executes `p4 filelog` on a given file specification. Returns an array of `P4.DepotFile` objects in tagged mode or an array of strings in non-tagged mode. It restructures the raw output into a more object-oriented format. ```python from P4 import P4, P4Exception p4 = P4() try: p4.connect() for r in p4.run_filelog( "index.html" )[0].revisions: for i in r.integrations: # Do something except P4Exception: for e in p4.errors: print(e) finally: p4.disconnect() ``` -------------------------------- ### P4 Python: Extend P4 Class with Custom Run Method Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.programming.html Illustrates how to extend the base P4 class in Python to create a custom P4 client. This example shows overriding the `run` method, ensuring that the original P4 `run` method is called with the provided arguments and keyword arguments. ```python class MyP4(P4.P4): def run(self, *args, **kargs): P4.P4.run(self, *args, **kargs) ``` -------------------------------- ### Get P4.Map as Array Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4_map.html Returns the entire P4.Map object represented as a list of strings, where each string is a mapping entry. ```python map_array = map_obj.as_array() print(map_array) ``` -------------------------------- ### Change Password using P4Python Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.programming.html Provides an example of how to change a user's password using the P4Python API. It shows the process of connecting to the server, authenticating with the old password, and then executing the password change command. The P4 object's password attribute is automatically updated. ```python from P4 import P4 p4 = P4() p4.user = "bruno" p4.password = "MyOldPassword" p4.connect() p4.run_password( "MyOldPassword", "MyNewPassword" ) # p4.password is automatically updated with the encoded password ``` -------------------------------- ### P4Python: Get P4 Environment Variable Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.classes.html Demonstrates how to retrieve the value of a Perforce Server environment variable using the `env()` method. This method accounts for P4CONFIG files and system-specific preferences. ```python from P4 import P4 p4 = P4() p4.connect() # Get the value of P4PORT p4port_value = p4.env('P4PORT') print(f'P4PORT is set to: {p4port_value}') p4.disconnect() ``` -------------------------------- ### Save Specification using p4.save_ Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html Provides shortcut methods to update Perforce specifications such as clients, labels, and branches. These methods are equivalent to setting the 'p4.input' attribute and then running the corresponding spec command with the '-i' flag. An example demonstrates saving a modified client specification. ```python from P4 import P4, P4Exception p4 = P4() try: p4.connect() client = p4.fetch_client() client[ "Owner" ] = p4.user p4.save_client( client ) except P4Exception: for e in p4.errors: print(e) finally: p4.disconnect() ``` -------------------------------- ### Instantiate and Connect to P4 Server using P4Python Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html Demonstrates the basic steps to instantiate a P4 object, set connection details, and establish a connection to the P4 Server. This is a prerequisite for executing any Perforce commands. ```python from P4 import P4 p4 = P4() p4.port = 'ssl:perforce.example.com:1666' p4.user = 'myuser' p4.password = 'mypassword' p4.client = 'myclient' p4.connect() ``` -------------------------------- ### Initialize and Configure P4 Client in Python Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.classes.html Demonstrates how to import the P4 module, initialize a P4 instance with specific connection parameters, and update configuration attributes like the user. ```python import P4 p4 = P4.P4(client="myclient", port="1666") p4.user = 'me' ``` -------------------------------- ### p4.ignore_file Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html Sets or gets the path to the ignore file. It defaults to P4IGNORE. This should be set before calling P4.is_ignored(). ```APIDOC ## p4.ignore_file ### Description Contains the path of the ignore file. It defaults to the value of `P4IGNORE`. Set `**P4.ignore_file**` prior to calling `P4.is_ignored()`. ### Method SET/GET ### Endpoint N/A (Attribute of P4 object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from P4 import P4 p4 = P4() p4.connect() p4.ignore_file = "/home/bruno/workspace/.ignore" # ... operations ... p4.disconnect() ``` ### Response #### Success Response (200) N/A (Attribute access) #### Response Example ``` "/home/bruno/workspace/.ignore" ``` ``` -------------------------------- ### Initialize and Connect to a P4 Server Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html Demonstrates how to initialize a local DVCS server using P4.init and manage the connection lifecycle with connect and disconnect methods. ```python import P4 p4 = P4.init( directory="/Users/sknop/dvcs/" ) p4.connect() # ... p4.disconnect() ``` -------------------------------- ### P4Python: Initialize a New P4 Server Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.classes.html Shows how to initialize a new, local Perforce P4 Server using the `init()` method. This is useful for setting up local development environments. ```python from P4 import P4 # Initialize a new P4 server in the current directory p4_server = P4().init() print("New P4 server initialized.") # You can then connect to this newly initialized server p4_server.connect() ``` -------------------------------- ### P4 Python: Create Client Workspace from Template and Sync Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.programming.html This script shows how to create a new client workspace based on a specified template and then synchronize it. It retrieves the client specification, modifies the root directory, saves the client, and performs a sync operation. Includes basic error handling. ```python from P4 import P4, P4Exception template = "my-client-template" client_root = "C:\\work\\my-root" p4 = P4() try: p4.connect() client = p4.fetch_client( "-t", template ) client._root = client_root p4.save_client( client ) p4.run_sync() except P4Exception: # Log errors and re-raise pass ``` -------------------------------- ### p4.password Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html Sets or gets the user's password or login ticket for the P4 Server. It can also be used with p4.run_login() to obtain a session ticket. ```APIDOC ## p4.password ### Description Contains your P4 Server 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 P4 Server 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 allocated by the server. ### Method SET/GET ### Endpoint N/A (Attribute of P4 object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from P4 import P4 p4 = P4() p4.password = "mypass" p4.connect() p4.run_login() print(f"Login ticket: {p4.password}") p4.disconnect() ``` ### Response #### Success Response (200) N/A (Attribute access) #### Response Example ``` "your_login_ticket_here" ``` ``` -------------------------------- ### Initialize and Clone P4 Instances Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html Methods for creating a new P4 object or cloning a remote service into a local P4 server instance. ```python import P4 # Construct new object p4 = P4.P4() # Clone using remotespec p4_remote = P4.clone("-p", "port", "-r", "remotespec") # Clone using filespec p4_file = P4.clone("-p", "port", "-f", "filespec") ``` -------------------------------- ### Get Right-Hand Side (RHS) of P4.Map Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4_map.html Returns a list containing the right-hand side (target) paths of all mappings in the P4.Map object. ```python rhs_paths = map_obj.rhs() print(rhs_paths) ``` -------------------------------- ### Get Left-Hand Side (LHS) of P4.Map Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4_map.html Returns a list containing the left-hand side (source) paths of all mappings in the P4.Map object. ```python lhs_paths = map_obj.lhs() print(lhs_paths) ``` -------------------------------- ### p4.host Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html Sets or gets the hostname of the Perforce Helix Core server. It defaults to P4HOST from P4CONFIG or environment variables. This must be configured before connecting to the server. ```APIDOC ## p4.host ### Description 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 P4 Server convention. Must be called before connecting to the P4 Server. ### Method SET/GET ### Endpoint N/A (Attribute of P4 object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from P4 import P4 p4 = P4() p4.host = "workstation123.perforce.com" p4.connect() # ... operations ... p4.disconnect() ``` ### Response #### Success Response (200) N/A (Attribute access) #### Response Example ``` "workstation123.perforce.com" ``` ``` -------------------------------- ### Configure P4 Connection Settings Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html Demonstrates how to configure various P4 instance attributes such as streams, tagged output, ticket files, user identity, and version tracking. ```python from P4 import P4 p4 = P4() # Configure streams and tagged output p4.streams = False p4.tagged = False # Set user and ticket file p4.user = "username" p4.ticket_file = "/root/.p4tickets" # Set version and connect p4.version = "123" p4.connect() print(p4.streams, p4.tagged) p4.disconnect() ``` -------------------------------- ### P4Python: Initialize and Connect to P4 Server Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.classes.html Demonstrates how to initialize a P4 object and establish a connection to a Perforce Helix Core server. This is a fundamental step before executing any commands. ```python from P4 import P4 p4 = P4() p4.port = 'ssl:perforce.example.com:1666' p4.user = 'myuser' p4.password = 'mypassword' p4.connect() ``` -------------------------------- ### Monitor Performance and Warnings Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html Shows how to enable server performance tracking and retrieve warnings generated during command execution. ```python from P4 import P4, P4Exception p4 = P4() # Enable tracking p4.track = 1 p4.run_info() print(p4.track_output) # Handle warnings try: p4.connect() p4.exception_level = 2 p4.run_sync() except P4Exception: for w in p4.warnings: print(w) finally: p4.disconnect() ``` -------------------------------- ### Basic P4 Python Script: Connect, Run Info, Edit, Disconnect Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.programming.html Demonstrates the fundamental structure of a P4 API for Python script. It establishes a connection to the P4 Server, runs the 'info' command to retrieve server details, edits a file, and then disconnects. Error handling using try-except blocks is included. ```python from P4 import P4,P4Exception p4 = P4() p4.port = "1666" p4.user = "fred" p4.client = "fred-ws" try: p4.connect() info = p4.run( "info" ) for key in info[0]: print key, "=", info[0][key] p4.run( "edit", "file.txt" ) p4.disconnect() except P4Exception: for e in p4.errors: print e ``` -------------------------------- ### P4.Map Class Methods Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4_map.html Documentation for the P4.Map class constructor and the `join` class method. ```APIDOC ## P4.Map Class ### Description The `**P4.Map**` class allows users to create and work with P4 Server mappings, without requiring a connection to a P4 Server. ## Class Methods ### P4.Map( [ list ] ) -> P4.Map Constructs a new `**P4.Map**` object. ### P4.Map.join ( map1, map2 ) -> P4.Map Join two `**P4.Map**` objects and create a third. The new map is composed of the left-hand side of the first mapping, as joined to the right-hand side of the second mapping. #### Example ```python # Map depot syntax to client syntax client_map = P4.Map() client_map.insert( "//depot/main/ப்புகளை", "//client/ப்புகளை" ) # Map client syntax to local syntax client_root = P4.Map() client_root.insert( "//client/ப்புகளை", "/home/bruno/workspace/ப்புகளை" ) # Join the previous mappings to map depot syntax to local syntax local_map = P4.Map.join( client_map, client_root ) local_path = local_map.translate( "//depot/main/www/index.html" ) # local_path is now /home/bruno/workspace/www/index.html ``` ``` -------------------------------- ### Fetch Perforce Specifications Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html Demonstrates using fetch methods to retrieve spec objects like labels, changes, and clients. These methods act as shortcuts for running the corresponding p4 command with the -o flag. ```python label = p4.fetch_label( "_labelname_" ) change = p4.fetch_change( _changeno_ ) clientspec = p4.fetch_client( "_clientname_" ) ``` ```python label = p4.run( "label", "-o", "_labelname_" )[0] change = p4.run( "change", "-o", _changeno_ )[0] clientspec = p4.run( "client", "-o", "_clientname_" )[0] ``` -------------------------------- ### Class: P4.DepotFile Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4_depotfile.html Represents a file within a P4 depot, containing file summary information and a collection of revision objects. ```APIDOC ## Class P4.DepotFile ### Description Utility class providing easy access to the attributes of a file in a P4 Server depot. Each P4.DepotFile object contains summary information about the file and a list of revisions (P4.Revision objects). ### Instance Attributes - **df.depotFile** (string) - The name of the depot file to which this object refers. - **df.revisions** (list) - A list of P4.Revision objects, one for each revision of the depot file. ### Usage This class is primarily instantiated via the `P4.run_filelog()` method. ### Example ```python # Example usage of P4.DepotFile files = p4.run_filelog('//depot/main/file.txt') for file_obj in files: print(f"File: {file_obj.depotFile}") for rev in file_obj.revisions: print(f"Revision: {rev.rev}") ``` ``` -------------------------------- ### Timestamp Conversion using Python datetime Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.programming.html Illustrates how to convert P4 API timestamp data, which is typically represented as seconds since the Epoch, into a human-readable datetime format. This example utilizes Python's built-in `datetime` module for the conversion. ```python import datetime # Assuming 'timestamp' is a variable holding seconds since Epoch myDate = datetime.datetime.fromtimestamp(timestamp, datetime.UTC) ``` -------------------------------- ### Execute P4 Commands with p4.run() Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html The base interface for running P4 Server commands. It accepts a command and a list of arguments, returning a list of results. Output format (strings or dictionaries) depends on server support for tagged output and whether it's enabled. P4Exception is raised for errors. ```python from P4 import P4 p4 = P4() p4.connect() spec = p4.run( "client", "-o" )[0] p4.disconnect() ``` -------------------------------- ### P4.Map Instance Methods Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4_map.html Documentation for instance methods of the P4.Map class, including `clear`, `count`, `is_empty`, `insert`, `translate`, `includes`, `reverse`, `lhs`, `rhs`, and `as_array`. ```APIDOC ## P4.Map Instance Methods ### map.clear() Empty a map. ### map.count() -> int Return the number of entries in a map. ### map.is_empty() -> boolean Test whether a map object is empty. ### map.insert( string …​ ) Inserts an entry into the map. 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. #### Examples ```python # called with two arguments: map.insert( "//depot/main/ப்புகளை", "//client/ப்புகளை" ) # called with one argument containing both halves of the mapping: map.insert( "//depot/live/... //client/live/..." ) # called with one argument containing a half-map: # This call produces the mapping "depot/... depot/..." map.insert( "depot/..." ) ``` ### map.translate ( string, [ boolean ] ) -> string 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. ### map.includes( string ) -> boolean Tests whether a path is mapped or not. #### Example ```python if map.includes( "//depot/main/..." ): ... ``` ### map.reverse() -> P4.Map Return a new `**P4.Map**` object with the left and right sides of the mapping swapped. The original object is unchanged. ### map.lhs() -> list Returns the left side of a mapping as an array. ### map.rhs() -> list Returns the right side of a mapping as an array. ### map.as_array() -> list Returns the map as an array. ``` -------------------------------- ### P4Python: Run a Specific Command Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.classes.html Demonstrates the convenience method `run__cmd_()` which is a direct wrapper around `P4.run('_command_')`. This provides a slightly more readable way to execute specific commands. ```python from P4 import P4 p4 = P4() p4.connect() # Run the 'info' command using run__cmd_ info_output = p4.run__cmd_('info') print(info_output) p4.disconnect() ``` -------------------------------- ### P4Python: Fetch a Spec Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.classes.html Illustrates how to fetch a Perforce specification (e.g., client, workspace) using the `fetch_spectype()` method. This is a convenient wrapper around `p4.run('', '-o')`. ```python from P4 import P4 p4 = P4() p4.connect() # Fetch the current user's client spec client_spec = p4.fetch_client('myclient') print(client_spec) p4.disconnect() ``` -------------------------------- ### Create Temporary Client using p4.temp_client Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html Creates a temporary Perforce client specification based on a provided template and prefix. It automatically switches the current client to the temporary one and sets up a temporary root directory. The temporary client is automatically deleted and the root removed upon exiting the 'with' block. ```python from P4 import P4 p4 = P4() p4.connect() with p4.temp_client( "temp", "my_template" ) as t: p4.run_sync() p4.run_edit( "foo" ) p4.run_submit( "-dcomment" ) p4.disconnect() ``` -------------------------------- ### Connect to P4 Server over SSL using P4Python Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.programming.html Demonstrates how to connect to a Perforce Helix Core server using the P4Python API. It highlights the use of the P4TRUST file for SSL certificate verification. If the server's fingerprint does not match the one in the P4TRUST file, the connection will fail. ```python from P4 import P4 p4 = P4() # Connection details would typically be set here, e.g., p4.port = "ssl:server:port" p4.connect() # Further operations... ``` -------------------------------- ### Iterate Through P4 Specification Objects Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html Shows how to use shortcut iteration methods like iterate_clients to process Perforce specification types efficiently. ```python for client in p4.iterate_clients(): # do something with the client spec ``` -------------------------------- ### P4Python: Run a P4 Command Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.classes.html Shows how to execute a raw Perforce command using the `run()` method of the P4 object. This method requires an active connection to the server. ```python from P4 import P4 p4 = P4() p4.connect() # Example: Get the current user's depot files files = p4.run('files', '//depot/...') for file in files: print(file) p4.disconnect() ``` -------------------------------- ### Create Temporary Client - P4Python Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.classes.html Creates a temporary client workspace on the Perforce Helix Core server. Useful for short-lived operations. ```python p4.temp_client() ``` -------------------------------- ### P4 Python: Login with Password Authentication Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.programming.html Shows how to log into a P4 Server using username and password authentication. This is necessary on servers that require explicit login before executing commands. After connecting, it runs the 'login' command and then retrieves opened files. ```python from P4 import P4 p4 = P4() p4.user = "bruno" p4.password = "my_password" p4.connect() p4.run_login() opened = p4.run_opened() ... ``` -------------------------------- ### Manage P4 Server Connections Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html Illustrates manual connection management and the use of the context manager pattern for automatic disconnection. ```python import P4 p4 = P4.P4() with p4.connect(): # block in context of connection ... ``` -------------------------------- ### p4.run_resolve() Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html Handles file resolution, supporting both automated and interactive resolution strategies. ```APIDOC ## METHOD p4.run_resolve([resolver], [args]) ### Description Performs a file resolve. For interactive resolves, a P4.Resolver object must be provided. ### Parameters - **resolver** (P4.Resolver) - Optional - An object derived from P4.Resolver for custom merge logic. - **args** (list) - Optional - Standard resolve flags (e.g., '-at', '-am'). ### Response - **Returns** (list) - Results of the resolve operation. ``` -------------------------------- ### p4.run_filelog() Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html A specialized method to retrieve file history information, returning structured P4.DepotFile objects. ```APIDOC ## METHOD p4.run_filelog(fileSpec) ### Description Runs 'p4 filelog' on the specified file and returns an array of P4.DepotFile objects for easy iteration over revisions and integrations. ### Parameters - **fileSpec** (string) - Required - The file path or depot path to query. ### Response - **Returns** (list) - An array of P4.DepotFile objects. ``` -------------------------------- ### p4.run() Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html The base interface for executing any Perforce command. It returns a list of results and handles tagged or non-tagged output based on server configuration. ```APIDOC ## METHOD p4.run(cmd, *args) ### Description Executes a P4 Server command with the provided arguments. Arguments should be passed as individual strings. ### Parameters - **cmd** (string) - Required - The Perforce command to execute. - **args** (list) - Optional - Command-specific options and arguments. ### Request Example ```python p4.run("print", "-o", "test-print", "//depot/file.c") ``` ### Response - **Returns** (list) - A list of dictionaries (tagged) or strings (non-tagged) containing command output. ``` -------------------------------- ### P4Python Core Methods Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.classes.html Commonly used P4Python methods for interacting with the Perforce server, including file logging, authentication, and changelist submission. ```APIDOC ## [METHOD] run_filelog ### Description Returns a list of P4.DepotFile objects representing the file history. ### Method Python Method ### Parameters #### Query Parameters - **args** (list) - Optional - File paths to retrieve logs for. ### Response #### Success Response (200) - **list** (P4.DepotFile) - A list of depot file objects. --- ## [METHOD] run_submit ### Description Convenience method for submitting changelists. When invoked with a change spec, it submits the spec. ### Method Python Method ### Request Body - **spec** (object) - Required - The changelist specification to submit. ### Request Example { "change": "new", "files": ["//depot/file.txt"] } ``` -------------------------------- ### Submit Changelist using p4.run_submit Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html Submits a changelist to the Perforce server. This can be done by providing a changelist object with updated fields or by passing arguments directly as they would appear on the command line. Ensure the changelist has the required fields set before submission. ```python from P4 import P4 p4 = P4() p4.connect() # Submit using a changelist object change = p4.fetch_change() change._description = "Some description" p4.run_submit( "-r", change ) # Submit using command-line arguments p4.run_submit( "-d", "Some description", "somedir/..." ) p4.disconnect() ``` -------------------------------- ### P4Python: Clone P4 Service Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.classes.html Shows how to clone a Perforce P4 Service into a local P4 Service using the `clone()` method. This returns a new `P4` object representing the cloned service. ```python from P4 import P4 # Assuming 'source_p4' is an already connected P4 object source_p4 = P4() source_p4.connect() # Clone the service to a new local P4 object cloned_p4 = source_p4.clone() print("P4 service cloned successfully.") source_p4.disconnect() ``` -------------------------------- ### Run File Log - P4Python Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.classes.html Retrieves a list of P4.DepotFile objects, representing file history in the depot. This is a specialized version of the P4.run() method. ```python p4.run_filelog(depot_file_path) ``` -------------------------------- ### P4.Integration Class Reference Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4_integration.html Details regarding the P4.Integration class attributes representing integration records. ```APIDOC ## P4.Integration Class ### Description Utility class providing easy access to the details of an integration record. This class is typically instantiated via the `P4.run_filelog()` method. ### Instance Attributes - **integ.how** (string) - The type of the integration record, describing how the record was created. - **integ.file** (string) - The path to the file being integrated to or from. - **integ.srev** (int) - The start revision number used for this integration. - **integ.erev** (int) - The end revision number used for this integration. ### Usage Example ```python # Example of accessing integration records from filelog filelogs = p4.run_filelog('//depot/main/file.txt') for filelog in filelogs: for integ in filelog.integrations: print(f"Integrated from: {integ.file} using method: {integ.how}") ``` ``` -------------------------------- ### P4 Python: Login with Ticket-Based Authentication and Custom Ticket Path Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.programming.html Demonstrates logging into a P4 Server using an authentication ticket. It covers setting a custom path for the ticket file using an environment variable (`P4TICKETS`) and directly within the P4 object. This method is used after an initial password-based login creates the ticket. ```python import os from P4 import P4 # Optional: Set a custom file path to ticket location os.environ["P4TICKETS"] = "/path/to/custom/.p4tickets" p4 = P4() # Optional: Set the ticket file directly in P4 object (redundant if using env var) p4.ticket_file = "/path/to/custom/.p4tickets" p4.user = "bruno" p4.password = "my_password" p4.connect() p4.run_login() opened = p4.run_opened() ... ``` -------------------------------- ### Implement a custom P4.OutputHandler subclass Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4_outputhandler.html This snippet demonstrates how to create a custom handler by subclassing P4.OutputHandler and overriding the output methods. The handler returns status flags to control whether the server output is reported or handled internally. ```python from P4 import P4, OutputHandler class MyHandler(OutputHandler): def outputStat(self, stat): print(f"Stat: {stat}") return OutputHandler.HANDLED def outputInfo(self, info): print(f"Info: {info}") return OutputHandler.REPORT p4 = P4() p4.connect() p4.handler = MyHandler() p4.run("info") ``` -------------------------------- ### Working with Spec Comments in P4Python Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.programming.html Demonstrates how to handle comments within Perforce specifications (specs) using the P4Python API. It shows how comments are preserved by default when parsing and formatting specs, and how to use alternative methods (`parse_spec`, `format_spec`) to strip comments if needed. This functionality was introduced in P4API for Python 2012.3. ```python from P4 import P4 p4 = P4() p4.connect() # fetch a client spec in raw format, no formatting: specform = p4.run( 'client', '-o', tagged=False )[0] # convert the raw document into a spec client1 = p4.parse_client( specform ) # comments are preserved in the spec as well print( client1.comment ) # comments can be updated client1.comment += "# ... and now for something completely different" # the comment is prepended to the spec ready to be sent to the user formatted1 = p4.format_client( client1 ) # or you can strip the comments client2 = p4.parse_spec( 'client', specform ) formatted2 = p4.format_spec( 'client', specform ) ``` -------------------------------- ### P4Python: Format a Spec Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.classes.html Demonstrates how to convert a Perforce specification (represented as a dictionary) into its string representation using the `format_spectype()` method. This is useful for preparing specs for submission or display. ```python from P4 import P4 p4 = P4() p4.connect() # Example: Format a client spec dictionary client_spec_dict = { 'Client': 'myclonedclient', 'Owner': 'myuser', 'Root': '/path/to/workspace' } formatted_spec = p4.format_client(client_spec_dict) print(formatted_spec) p4.disconnect() ``` -------------------------------- ### Configure Character Set for Unicode P4 Server Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html Illustrates setting the character set for connecting to a Unicode-enabled P4 Server. This is important for correct data handling. The default is the `P4CHARSET` environment variable. An invalid character set will raise a `P4Exception`. ```python from P4 import P4 p4 = P4() p4.client = "www" p4.charset = "iso8859-1" p4.connect() p4.run_sync() p4.disconnect() ``` -------------------------------- ### Submit Changelist - P4Python Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.classes.html Convenience method for submitting changelists to the Perforce Helix Core server. Can submit a changelist specification directly. ```python p4.run_submit(changelist_spec=None) ``` -------------------------------- ### P4Python: Parse a Spec Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.classes.html Illustrates how to parse a string representation of a Perforce specification into a dictionary using the `parse_spectype()` method. This is useful when reading specs from files or command output. ```python from P4 import P4 p4 = P4() p4.connect() # Example: Parse a changelist spec string changelist_spec_string = ''' Change: 12345 Client: myclient User: myuser Status: pending Description: Initial commit. ''' parsed_spec = p4.parse_change(changelist_spec_string) print(parsed_spec) p4.disconnect() ``` -------------------------------- ### Provide input for P4 commands Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html Sets the input data for the next command execution. This is commonly used for submitting changes or providing data to commands requiring user input. ```python from P4 import P4 p4 = P4() p4.connect() change = p4.run_change( "-o" )[0] change[ "Description" ] = "Autosubmitted changelist" p4.input = change p4.run_submit( "-i" ) p4.disconnect() ``` -------------------------------- ### Format and Parse Specifications Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html Methods to convert between P4 server form strings and Python dictionaries. Shortcuts are available for specific spec types like client, branch, or job. ```python # Formatting example p4.format_spec( "<_spectype_>", dict ) # Shortcut equivalent p4.format_<_spectype_>( dict ) # Parsing example p4.parse_spec( "<_spectype_>", buf ) # Shortcut equivalent p4.parse_<_spectype_>( buf ) ``` -------------------------------- ### Construct P4.Map Object Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4_map.html Creates a new P4.Map object. This object can be initialized with an optional list of existing mappings. ```python map_obj = P4.Map() # or with an initial list # map_obj = P4.Map([ "//depot/... //client/..." ]) ``` -------------------------------- ### Set API Compatibility Level in P4Python Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html Shows how to set the API compatibility level for the P4Python client. This is crucial for ensuring script compatibility with older P4 Server releases, especially when dealing with commands that do not yet support tagged output. Must be called before `P4.connect()`. ```python from P4 import P4 p4 = P4() p4.api_level = 67 # Lock to 2010.1 format p4.connect() ... p4.disconnect() ``` -------------------------------- ### Perform P4 Resolve with p4.run_resolve() Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.p4.html Executes the `p4 resolve` command. For interactive resolves, it requires a `P4.Resolver` object. For automated merges, it can accept arguments like `"-at"` to skip conflicts. ```python p4.run_resolve ( "-at" ) ``` -------------------------------- ### P4Python: Iterate Through Specs Source: https://help.perforce.com/helix-core/apis/p4python/current/Content/P4Python/python.classes.html Shows how to iterate through multiple Perforce specifications of a given type (e.g., jobs, labels) using the `iterate_spectype()` method. This is efficient for processing large numbers of specs. ```python from P4 import P4 p4 = P4() p4.connect() # Iterate through all jobs for job in p4.iterate_job(): print(job['job']) p4.disconnect() ```