-
-
Save krzemienski/8c7e8e76c8652984cca0da3fea5b5368 to your computer and use it in GitHub Desktop.
Python subprocess logging to logger from stdout/stderr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/local/bin/python3 | |
import logging, select, subprocess | |
LOG_FILE = "test.log" | |
logger = logging.getLogger(__name__) | |
logging.basicConfig(level=logging.INFO,filename=LOG_FILE,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') | |
def logging_call(popenargs, **kwargs): | |
process = subprocess.Popen(popenargs, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) | |
def check_io(): | |
while True: | |
output = process.stdout.readline().decode() | |
if output: | |
logger.log(logging.INFO, output) | |
else: | |
break | |
# keep checking stdout/stderr until the child exits | |
while process.poll() is None: | |
check_io() | |
def main(): | |
logging_call(["ls", "-l"]) | |
if __name__ == "__main__": | |
try: | |
main() | |
except KeyboardInterrupt: | |
logging.warning("Stopping...") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment