Quick start for P4 API for Python on Windows
On this page:
Before you begin
Ensure you have the following:
-
Access to a working version of P4 Server.
-
The server and port values for P4 Server.
-
The username for your P4 user.
-
The name of the workspace that contains the files you want to check out, edit, and commit.
-
(Optional) A working version of P4V, to check if a file has been added to a changelist.
Install P4 API for Python
The easiest way to install the P4 API for Python is to use the terminal and install the package with pip.
-
To install P4 API for Python, run:
pip install p4python -
(Optional) To verify P4 API for Python is installed, run:
pip show p4pythonIf installed, pip displays P4 API for Python information.
Alternatively, to install P4 API for Python from source:
-
Download the official source code from the Perforce GitHub repository.
-
Follow the instructions in the
BUILD.mdfile, also hosted on GitHub repository.
For more information on installing P4 API for Python, see Installing P4 API for Python
Connect the API to P4 Server
Use the following script to connect to P4 Server and view the first ten files in a given workspace.
Update the following credentials in the script:
-
p4.port- Add the server and port to connect to in the format:server:port -
p4.user- A username for your P4 user. -
p4.client- The name of the workspace you want to connect to.
Call the script something simple like connect_to_p4.py
from P4 import P4, P4Exception
def main():
p4 = P4()
# --- Tailor these to your environment ---
p4.port = "localhost:1666" # server:port
p4.user = "P4UserName" # username
p4.client = "python_projects_main" # workspace name
# If your server is in Unicode mode, set a charset:
# IMPORTANT: do NOT set p4.charset on a non-Unicode server
#p4.charset = "utf8"
try:
p4.connect()
info = p4.run("info")[0]
print("Connected to:", info.get("serverAddress"))
files = p4.run("have")[:10]
# displays up to the first 10 files
for f in files:
print(" -", f.get("depotFile"), "#", f.get("rev"))
except P4Exception:
for e in p4.errors:
print("P4 error:", e)
finally:
if p4.connected():
p4.disconnect()
print("Disconnected from the P4 Server.")
if __name__ == "__main__":
main()
To run the script:
-
Open a terminal and navigate to the folder containing the script.
-
Run
py connect_to_p4.py(If you have given the script a different name, use that name). -
Check the output.
You should see up to 10 files listed in your chosen workspace.
If you receive any errors when connecting to the P4 Server, see Troubleshooting.
Check out a file
The following script will:
-
Connect to P4 Server with your credentials (user and workspace).
-
Create a pending changelist with a simple description.
-
Open the target file for edit in that changelist.
-
Return a brief summary of what has been done.
-
This returns a changelist number. This number is needed when submitting the file.
-
-
Disconnect from the P4 Server cleanly.
Update the following credentials in the script:
-
P4PORT- Add the server and port to connect to in the format:server:port -
P4USER- A username for your P4 user. -
P4CLIENT- The name of the workspace you want to connect to. -
DEPOT_FILE- Filepath to the file to edit. For example://DemoDepot/python/Ascii_art/README.md
Call the script something simple like check_out_file.py
from P4 import P4, P4Exception
from datetime import datetime
def main():
P4PORT = "localhost:1666"
P4USER = "P4UserName"
P4CLIENT = "python_projects_main"
DEPOT_FILE = "//DemoDepot/python/Ascii_art/README.md"
p4 = P4()
p4.port = "localhost:1666"
p4.user = "P4Andy"
p4.client = "python_projects_main"
try:
p4.connect()
info = p4.run("info")[0]
print(f"Connected to {info.get('serverAddress')} (workspace: {P4CLIENT})")
# 1) Create a pending changelist with a short description
change = p4.fetch_change()
change._description = f"Edit {DEPOT_FILE} via P4Python ({datetime.now():%Y-%m-%d %H:%M:%S})"
saved = p4.save_change(change) # e.g., ['Change 12345 created.']
cl_number = int(saved[0].split()[1])
print(f"Created changelist {cl_number}")
# 2) Open the file for edit in that changelist
p4.run("edit", "-c", str(cl_number), DEPOT_FILE)
print(f"Opened for edit: {DEPOT_FILE} (cl {cl_number})")
# 3) Show a short “opened” summary
opened_now = p4.run("opened", DEPOT_FILE)
for o in opened_now:
print(f"{o.get('depotFile')} ({o.get('action')}) cl={o.get('change')} -> {o.get('clientFile')}")
print(f"Changelist number: {cl_number}")
print("Make a note of this number. You will need it to submit the file.")
except P4Exception:
for e in p4.errors:
print("P4 error:", e)
finally:
if p4.connected():
p4.disconnect()
print("Disconnected from the P4 Server.")
if __name__ == "__main__":
main()
To run the script:
-
Open a terminal and navigate to the folder containing the script.
-
Run
py check_out_file.py(If you have given the script a different name, use that name) -
Make a note of the changelist number. You will need this to commit the file.
Your chosen file is now available to edit.
If you have P4V, you will see a new changelist with your selected file.
Commit a file
The following script will:
-
Prompt you for the changelist number.
-
This changelist number was output in the previous section.
-
-
Connect to the P4 Server
-
Fetch the changelist to ensure it’s pending.
-
Show the current description, then prompt you to add any more detail for the changelist description.
-
Submit the changelist and prints the result.
-
Disconnect from P4 Server.
Update the following credentials in the script:
-
P4PORT- Add the server and port to connect to in the format:server:port -
P4USER- A username for your P4 user. -
P4CLIENT- The name of the workspace you want to connect to.
Call the script something simple like commit_file.py
from P4 import P4, P4Exception
import sys
def main():
# ---- Tailor these values ----
P4PORT = "localhost:1666"
P4USER = "P4UserName"
P4CLIENT = "python_projects_main"
# Get changelist number (argument or prompt)
if len(sys.argv) != 2:
cl_number = input("Enter the changelist number to submit: ").strip()
else:
cl_number = sys.argv[1]
if not cl_number:
print("No changelist number provided. Exiting.")
sys.exit(1)
p4 = P4()
p4.port = P4PORT
p4.user = P4USER
p4.client = P4CLIENT
try:
p4.connect()
info = p4.run("info")[0]
print(f"Connected to {info.get('serverAddress')} (workspace: {P4CLIENT})")
# Fetch the change to validate and optionally update description
change = p4.fetch_change(cl_number)
status = (change.get("Status") or "").lower()
if status != "pending":
print(f"Changelist {cl_number} is not pending (status: {change.get('Status')}).")
return
# Show current description
print(f"Current description:\n---\n{change.get('Description','').rstrip()}\n---")
user_note = input("Add a submit comment (leave blank to keep as-is): ").strip()
if user_note:
base_desc = change.get("Description", "").rstrip()
new_desc = (base_desc + "\n\n" if base_desc else "") + user_note
change._description = new_desc
p4.save_change(change)
print("Updated changelist description.")
# Submit the changelist
result = p4.run("submit", "-c", cl_number)
print("Submit result:")
for entry in result:
print(" ", entry)
print(f"Submitted changelist {cl_number}")
except P4Exception:
for e in p4.errors:
print("P4 error:", e)
finally:
if p4.connected():
p4.disconnect()
print("Disconnected from the P4 Server.")
if __name__ == "__main__":
main()
To run the script:
-
Open a terminal and navigate to the folder containing the script.
-
Run
py commit_file.py. -
When asked, enter the changelist number with the file you want to commit.
-
(Optional) Enter a changelist description.
Your chosen file has now been committed. If you check P4V, you will no longer be able to see the pending changelist.
Next steps
View the documentation for P4 API for Python Classes to see what other commands are available when using P4 API for Python.