Decorate \ delegate a File object to add functionality

后端 未结 5 900
忘掉有多难
忘掉有多难 2020-12-03 01:57

I\'ve been writing a small Python script that executes some shell commands using the subprocess module and a helper function:

import subprocess          


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-03 02:31

    This simple solution worked for me:

    import sys
    import datetime
    import tempfile
    import subprocess as sp
    def run(command, description):
        """Runs a command in a formatted manner. Returns its return code."""
        with tempfile.SpooledTemporaryFile(8*1024) as so:
            print >> sys.stderr, '%-65s' % description
            start=datetime.datetime.now()
            retcode = sp.call(command, shell=True, stderr=sp.STDOUT, stdout=so)
            end=datetime.datetime.now()
            so.seek(0)
            for line in so.readlines():
                print >> sys.stderr,'logging this:', line.rstrip()
            duration=end-start
            status='Done' if retcode == 0 else 'Failed'
            print >> sys.stderr, '%s (%d seconds)' % (status, duration.seconds)
    
    REF_SCRIPT = r"""#!/usr/bin/python
    import sys
    
    sys.stdout.write('OUT\n')
    sys.stdout.flush()
    sys.stderr.write('ERR\n')
    sys.stderr.flush()
    """
    
    SCRIPT_NAME = 'refscript.py'
    
    if __name__ == '__main__':
        with open(SCRIPT_NAME, 'w') as script:
            script.write(REF_SCRIPT)
        run('python ' + SCRIPT_NAME, 'Reference script')
    

提交回复
热议问题