P4Python: Perforce Helix Core API
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
-
P4Exception: connect: P4PORT not set.
cause The `P4PORT` environment variable is not set, and `p4.port` was not explicitly configured in the script.fixBefore `p4.connect()`, ensure you set `p4.port = 'your_server:your_port'` (e.g., `p4.port = 'perforce:1666'`) or set the `P4PORT` environment variable. -
P4Exception: Not connected!
cause A Perforce command was attempted before `p4.connect()` was successfully called.fixEnsure `p4.connect()` is called and succeeds before attempting to run any Perforce commands like `p4.run('info')`. -
P4Exception: client 'your_client' unknown - use 'p4 client' to create it.
cause The client workspace specified by `p4.client` or the `P4CLIENT` environment variable does not exist on the server or is not accessible to the current user.fixVerify that `p4.client` is set to an existing, valid client workspace name. You may need to create a new client workspace using `p4 client` on the command line or `p4.run('client', '-i', client_spec)` in your script. -
UnicodeDecodeError: 'utf-8' codec can't decode byte ...
cause Perforce server output contains characters that Python's default decoder cannot handle, often due to mismatched `charset` settings between client and server.fixSet `p4.charset = 'utf8'` (or the appropriate charset like 'shiftjis', 'iso8859-1') after initializing `P4()` and before `p4.connect()`. Ensure your script's source file is also saved with the correct encoding (e.g., UTF-8).
Warnings
- gotcha Failing to disconnect from the Perforce server can leave open connections, consuming server resources and potentially causing issues for long-running scripts.
- gotcha P4Python's handling of Unicode and character encodings can be tricky, especially with older servers or mixed environments, potentially leading to `UnicodeDecodeError` or corrupted text.
- gotcha Relying solely on `P4PORT`, `P4USER`, `P4CLIENT`, `P4PASSWD` environment variables can lead to brittle scripts, especially when running multiple commands or managing different server/user contexts.
Install
-
pip install p4python
Imports
- P4
from P4 import P4
- P4Exception
from P4 import P4Exception
Quickstart
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.")