How do I check out a file from perforce in python?

I would like to write some scripts in python that do some automated changes to source code. If the script determines it needs to change the file I would like to first check it out of perforce. I don't care about checking in because I will always want to build and test first.

Asked by: Melissa302 | Posted: 24-09-2021

Answer 1

Perforce has Python wrappers around their C/C++ tools, available in binary form for Windows, and source for other platforms:

You will find their documentation of the scripting API to be helpful:

Use of the Python API is quite similar to the command-line client:

PythonWin 2.5.1 (r251:54863, May  1 2007, 17:47:05) [MSC v.1310 32 bit (Intel)] on win32.
Portions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin' for further copyright information.
>>> import P4
>>> p4 = P4.P4()
>>> p4.connect() # connect to the default server, with the default clientspec
>>> desc = {"Description": "My new changelist description",
...         "Change": "new"
...         }
>>> p4.input = desc
>>>"changelist", "-i")
['Change 2579505 created.']

I'll verify it from the command line:

P:\>p4 changelist -o 2579505
# A Perforce Change Specification.
#  Change:      The change number. 'new' on a new changelist.
#  Date:        The date this specification was last modified.
#  Client:      The client on which the changelist was created.  Read-only.
#  User:        The user who created the changelist.
#  Status:      Either 'pending' or 'submitted'. Read-only.
#  Description: Comments about the changelist.  Required.
#  Jobs:        What opened jobs are to be closed by this changelist.
#               You may delete jobs from this list.  (New changelists only.)
#  Files:       What opened files from the default changelist are to be added
#               to this changelist.  You may delete files from this list.
#               (New changelists only.)

Change: 2579505

Date:   2008/10/08 13:57:02


User:   myusername

Status: pending

        My new changelist description

Answered by: Grace731 | Posted: 25-10-2021

Answer 2

Here's what I came up with:

import os

def CreateNewChangeList(description):
    "Create a new changelist and returns the changelist number as a string"
    p4in, p4out = os.popen2("p4 changelist -i")
    p4in.write("change: new\n")
    p4in.write("description: " + description)
    changelist = p4out.readline().split()[1]
    return changelist

def OpenFileForEdit(file, changelist = ""):
    "Open a file for edit, if a changelist is passed in then open it in that list"
    cmd = "p4 edit "
    if changelist:
        cmd += " -c " + changelist + " "
    ret = os.popen(cmd + file).readline().strip()
    if not ret.endswith("opened for edit"):
        print "Couldn't open", file, "for edit:"
        print ret
        raise ValueError

Answered by: Sarah151 | Posted: 25-10-2021

Answer 3

Perforce's P4 Python module mentioned in another answer is the way to go, but if installing this module isn't an option you can use the -G flag to help parse p4.exe output:

p4 [ options ] command [ arg ... ]
            -c client -C charset -d dir -H host -G -L language
            -p port -P pass -s -Q charset -u user -x file
    The -G flag causes all output (and batch input for form commands
    with -i) to be formatted as marshalled Python dictionary objects.

Answered by: Ada208 | Posted: 25-10-2021

Answer 4

Building from p4python source requires downloading and extracting the p4 api recommended for that version. For example, if building the Windows XP x86 version of P4Python 2008.2 for activepython 2.5:

  • download and extract both the p4python and p4api
  • fixup the setup.cfg for p4python to point to the p4api directory.

To open files for edit (do a checkout), on the command line, see 'p4 help open'.

You can check out files without making a changelist if you add the file to the default changelist, but it's a good idea to make a changelist first.

P4Python doesn't currently compile for activepython 2.6 without visual studio 2008; the provided libs are built with 2005 or 2003. Forcing p4python to build against mingw is nearly impossible, even with pexports of python26.dll and reimp/reassembly of the provided .lib files into .a files.

In that case, you'll probably rather use subprocess, and return p4 results as marshalled python objects. You can write your own command wrapper that takes an arg array, constructs and runs the commands, and returns the results dictionary.

You might try changing everything, testing, and on success, opening the files that are different with something equivalent to 'p4 diff -se //...'

Answered by: Blake222 | Posted: 25-10-2021

Answer 5

You may want to check out the P4Python module. It's available on the perforce site and it makes things very simple.

Answered by: Anna540 | Posted: 25-10-2021

Answer 6

Remember guys to install the development package for Python for the p4api or it will complain about missing headers. In Ubuntu 10.10, just do a simple:

apt-get install python2.6-dev


apt-get install python3.1-dev

Answered by: Abigail346 | Posted: 25-10-2021

Similar questions

scripting - python as a "batch" script (i.e. run commands from python)

I'm working in a windows environment (my laptop!) and I need a couple of scripts that run other programs, pretty much like a windows batch file. how can I run a command from python such that the program when run, will replace the script? The program is interactive (for instance, unison) and keeps printing lines and asking for user input all the time. So, just running a program and printing the output won't...

scripting - What would be the simplest way to daemonize a python script in Linux?

What would be the simplest way to daemonize a python script in Linux ? I need that this works with every flavor of Linux, so it should only use python based tools.

scripting - Make python enter password when running a csh script

I'm writing a python script that executes a csh script in Solaris 10. The csh script prompts the user for the root password (which I know) but I'm not sure how to make the python script answer the prompt with the password. Is this possible? Here is what I'm using to execute the csh script: import commands commands.getoutput('server stop')

scripting - Python code for sorting files into folders

Python 2.5.1 I've just run PhotoRec and the code given as a way to sort file types into their own folder is coming back with this error. Any suggestions on how to alter? Thanks : [EDIT2: Two points: This question was voted down because it was a...

python - How can I call a DLL from a scripting language?

I have a third-party product, a terminal emulator, which provides a DLL that can be linked to a C program to basically automate the driving of this product (send keystrokes, detect what's on the screen and so forth). I want to drive it from a scripting language (I'm comfortable with Python and slightly less so with Perl) so that we don't have to compile and send out executables to our customers whenever there's a p...

scripting - Change directory to the directory of a Python script

How do I change directory to the directory with my Python script in? So far, I figured out I should use os.chdir and sys.argv[0]. I'm sure there is a better way then to write my own function to parse argv[0].

php - Get remote text file, process, and update database - approach and scripting language to use?

I've been having to do some basic feed processing. So, get a file via ftp, process it (i.e. get the fields I care about), and then update the local database. And similarly the other direction: get data from db, create file, and upload by ftp. The scripts will be called by cron. I think the idea would be for each type of feed, define the ftp connection/file information. Then there should be a translation of how data...

scripting - cProfile and Python: Finding the specific line number that code spends most time on

I'm using cProfile, pstats and Gprof2dot to profile a rather long python script. The results tell me that the most time is spent calling a method in an object I've defined. However, what I would really like is to know exactly what line number within that function is eating up the time. Any idea's how to get this additional information? (By the way, I'm using Python 2.6 on OSX snow leopard if that h...

php - How do scripting languages use sockets?

Python, Perl and PHP, all support TCP stream sockets. But exactly how do I use sockets in a script file that is run by a webserver (eg Apache), assuming I only have FTP access and not root access to the machine? When a client connects to a specific port, how does the script file get invoked? Does the script s...

html - Python for web scripting

I'm just starting out with Python and have practiced so far in the IDLE interface. Now I'd like to configure Python with MAMP so I can start creating really basic webapps — using Python inside HTML, or well, vice-versa. (I'm assuming HTML is allowed in Python, just like PHP? If not, are there any modules/template engines for that?) What modules do I need to install to run .py from my localhost? Googling a bit, it s...

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python