Howto: Execute a command and use the output in Python

Let’s do something very simple to show a couple of things:

  • How to script Plastic SCM commands;
  • How to execute a program in Python and do something useful with the output.

Say that you want to check if there’s been some activity in a specific Plastic SCM server in a period of time. To do that, a good idea is to check if new changesets have been created. But let’s suppose that you have hundreds of repositories, so you really don’t want to check ‘em all one by one, do you?

Right, so let’s write some Python code to achieve this:

from subprocess import Popen, PIPE

proc = Popen(["cm", "lrep", "--format={1}"],
    stdout=PIPE, stderr=PIPE)

repositories = proc.stdout.readlines()

for repository in repositories:
    repository = repository.replace('\n','')
    print "Repository: %r" % repository
    proc = Popen(
        ["cm",
         "find",
         "changesets where date > '01/01/2013' on repository '"+
         repository + "@localhost:8084'"
        ],
        stdout=PIPE, stderr=PIPE)
    print proc.stdout.read()
    print "------------------------------"

First, we import the required library we need to execute subprocesses and redirect output and errors. This is a quite common library. Then we create a child process to execute the command “cm lrep”, to get the list of repositories in that server. The format string is just to cut the output in order to get just the names of the repositories.

See that we are redirecting the standard output and the standard errors to a PIPE. Then we get the output of the command. This is one of the beauties of Python: with just one single line you get and parse in an array the different lines of the output🙂.

Now we iterate in the list of repositories we’ve just got, remove the EOL character and execute the proper command to query if there have been new changesets in the last year (this could have been calculated with the current date, or could have been an argument to the script).

We execute the cm find changeset command and get the output, and just print it in the console.

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s