bash - How use python subprocess.call, sending copy of stdout to logfile, while detecting result of first command -


my python script needs invoke program, detect if failed (eg, result != 0) , send output of program both stdout normal plus log file.

my default shell bash. i'm using python 2.7.9

to send output both stdout , file i'd use tee:

result = subprocess.call('some_program --an-option  | tee -a ' + logfile , shell=true) 

however, pipe in bash return true if first command fails, approach fails detect if command fails.

if try use set -o pipefail in command (so result indicate if first command fails) this:

result = subprocess.call('set -o pipefail && some_program --an_option  | tee -a ' + logfile , shell=true) 

i error /bin/sh: 1: set: illegal option -o pipefail

is there way in python invoke command, send output both normal stdout console , logfile, , still detect if command failed?

note: have continue sending some_program's output stdout since stdout being sent websocket.

i error /bin/sh: 1: set: illegal option -o pipefail

pass executable='/bin/bash' otherwise /bin/sh used.

you implement tee in pure python:

#!/usr/bin/env python2 import sys subprocess import popen, pipe  chunk_size = 1 << 13     p = popen(["some_program", "--an-option"], stdout=pipe, bufsize=1) p.stdout, open('logfile', 'ab') logfile:     chunk in iter(lambda: p.stdout.read(chunk_size), b''):         sys.stdout.write(chunk)         logfile.write(chunk) if p.wait() != 0:     raise error 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -