P4Python: Perforce Helix Core API

2025.2.2863679 · active · verified Thu Apr 16

P4Python is the official Python API for Perforce Helix Core, allowing Python applications to interact with Perforce servers. It enables scripting of Perforce operations like file management, changelists, jobs, and user administration. The library is actively maintained with frequent releases, currently at version 2025.2.2863679.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to establish a connection to a Perforce Helix Core server, run a basic 'info' command, and properly disconnect. It prioritizes using environment variables for credentials where possible, falling back to placeholders.

import os
from P4 import P4, P4Exception

# Configure connection details (prefer environment variables or explicit settings)
# Example: P4PORT='ssl:perforce:1666', P4USER='your_user', P4CLIENT='your_workspace'
p4_port = os.environ.get('P4PORT', 'perforce:1666') # Replace with your server:port
p4_user = os.environ.get('P4USER', 'guest')       # Replace with your Perforce username
p4_client = os.environ.get('P4CLIENT', 'cli_workspace') # Replace with your client workspace name
p4_password = os.environ.get('P4PASSWD', '')    # Only needed if using password authentication

try:
    # Initialize P4 object
    p4 = P4()

    # Set connection parameters
    p4.port = p4_port
    p4.user = p4_user
    p4.client = p4_client
    if p4_password:
        p4.password = p4_password

    # Connect to the Perforce server
    p4.connect()

    # Log in if required (if 'p4 login' is enforced)
    # p4.login()

    # Run a simple Perforce command
    info_output = p4.run('info')
    print(f"Successfully connected to Perforce server: {info_output[0]['serverAddress']}")
    print(f"Current Perforce user: {info_output[0]['userName']}")

    # Get a list of clients
    clients = p4.run('clients')
    print(f"Found {len(clients)} clients.")

except P4Exception as e:
    # P4Exception catches errors reported by the Perforce server or API
    for error_msg in e.errors:
        print(f"P4API Error: {error_msg}")
except Exception as e:
    # Catch other unexpected Python errors
    print(f"An unexpected error occurred: {e}")
finally:
    # Always ensure disconnection
    if 'p4' in locals() and p4.connected():
        p4.disconnect()
        print("Disconnected from Perforce server.")

view raw JSON →