python - How to redirect linux command output to logging -


i know simple question not able make new python

i have shell script generate out put when execute onlinux shell takes 30-40 min more finish script. using script in python code. when execute python script(say abc.py) output should redirect logging instantly should printed on screen.

ex: test.sh shell script , abc.py python script. can redirect complete output of test.sh logging below

import logging import commands logging,basicconfig(filename=abc.log,filemode='w',level=logging.info) print ("logging started") status,output=commands.getstatusoutput(./test.sh) logging.info(output)    

but here 2 drawbacks: 1) have wait till test.sh completed view output in abc.log file want view output instantly abc.log 2)even cann't view output on screen instantly , here have wait completes.

can guide better way fulfill goal.

as mentioned in comment, subprocess module more suited this. you'll have read data process through pipe, , log , print it.

here working example:

import logging import subprocess  logging.basicconfig(filename='abc.log', filemode='w', level=logging.info) print("logging started") popen = subprocess.popen('./script.sh', stdout=subprocess.pipe)  line in (s.strip('\n').strip('\r') s in iter(popen.stdout.readline, "")):     logging.info(line)     print line 

the code strips \r , \n character ends of string, don't end in log or output.


Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -