,

Python – sh – call shell commands and process results

# -*- coding: UTF-8 -*-
import os, sys
def main():
   res = sh('ls -l')
   print res

def sh(self,  cmd_arg_str, errout=sys.stderr ):
    import subprocess
    r""" Popen a shell -> line or "line1 \n line2 ...", trim last \n """
    # crashes after pyqt QApplication() with mac py 2.5.1, pyqt 4.4.2
    # subprocess.py _communicate select.error: (4, 'Interrupted system call')
    # see http://bugs.python.org/issue1068268 subprocess is not EINTR-safe
    # QProcess instead of Popen works
    (lines, err) = subprocess.Popen( cmd_arg_str,
         stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True ) \
                .communicate()  # wait til process ends
    if errout and err:
       print(err, file=errout)
    # trim the last \n so sh( "ls xx" ) -> "xx" not "xx\n"
    # and split( "\n" ) -> no extra ""
    return lines[:-1] if (lines and lines[-1] == "\n") \
       else lines


if __name__ == '__main__':
    main()


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *