Snippet: caller.py

Me suelo olvidar como usar el modulo subprocess asi que mantengo aca este snippet

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import subprocess
import shlex


class CallError(Exception):
    
    def __init__(self, cmd, stderr, code):
        msg = "External call '%s' fail with code '%i'. Cause: '%s'" % (cmd, 
                                                                                                  code, stderr)
        super(CallError, self).__init__(msg)
        self.cmd = cmd
        self.stderr = stderr
        self.code = code
                   

class Call(object):
    """Wraps a system call"""
    
    def __init__(self, cmd):
        """Creates a new instance of call
        
        @param cmd: the system command to be executed
        
        """
        self._cmd = cmd
        self._pcmd = shlex.split(cmd)

    def __repr__(self):
        return "<Call '%s' at %s>" % (self._cmd, hex(id(self)))

    def call(self):
        """Execute the cmd an return the standar output or raises an exception
        
        """
        p = subprocess.Popen(self._pcmd, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        stdout, stderr = p.communicate()
        if p.returncode:
            raise CallError(self.cmd, stderr, p.returncode)
        return stdout
        
    @property
    def cmd(self):
        return self._cmd

uso:

import caller
ls_lia = caller.Call("ls -lia")
print ls_lia.call()

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos necesarios están marcados *

Puedes usar las siguientes etiquetas y atributos HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>