import subprocess
from tempfile import TemporaryDirectory
from pathlib import Path

with TemporaryDirectory() as tmpdirname:
  with open(Path(tmpdirname) / "logfile.txt", 'w') as log_file:
    cmd = 'printf "%s\\n" "foo" "bar" "baz"'
    log_file.write("Running the command: %s\n" % cmd)
    log_file.flush()
    subprocess.call(cmd, shell=True, stdout=log_file, stderr=log_file)

  with open(Path(tmpdirname) / "logfile.txt", 'r') as read_file:
    for line in read_file:
        print(line, end='')
