Quick start for P4 API for Python on Windows

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.

  1. To install P4 API for Python, run:

    pip install p4python

  2. (Optional) To verify P4 API for Python is installed, run:

    pip show p4python

    If installed, pip displays P4 API for Python information.

Alternatively, to install P4 API for Python from source:

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

Copy
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:

  1. Open a terminal and navigate to the folder containing the script.

  2. Run py connect_to_p4.py (If you have given the script a different name, use that name).

  3. 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.

This script disconnects from the P4 Server because opening a file for edit is a one‑time server operation, not a live session. When a file is checked out it remains open until you submit or revert with no connection required.

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

Copy
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:

  1. Open a terminal and navigate to the folder containing the script.

  2. Run py check_out_file.py (If you have given the script a different name, use that name)

  3. 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.

  • 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

Copy
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:

  1. Open a terminal and navigate to the folder containing the script.

  2. Run py commit_file.py .

  3. When asked, enter the changelist number with the file you want to commit.

  4. (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.