Python Forum

Full Version: subprocess_run and stdout flux
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi

I'm wondering if it's possible to get the stdout flux to a file and the consalole at the same time (i.e. in real time); i've made the (basic) example bellow using ls -l (but of course in my case, it's much more complex).

Thanks for your help

Paul

Note: if the post name includes subprocess.run, iy is considered as a spam Confused

import os, subprocess

Path = os.getcwd()
Outputfile = "output.txt"
command_line = "ls -l"
args = command_line.split()
result = subprocess.run(args, stdout = open(Path + '/' + Outputfile, 'w'))
print(result.stdout)
You can use check_output

from os import getcwd
from subprocess import check_output
 
path = getcwd()
output_file = "output.txt"
command_line = "ls -l"
args = command_line.split()
output_text = check_output(args, shell = True).decode()
print(output_text)

with open(f"{path}/{output_file}", "w") as f:
    f.write(output_text)
In Linux, you could compose with the tee command
import subprocess as sp
ls = sp.Popen(['ls', '-l'], stdout=sp.PIPE)
tee = sp.run(['tee', 'output.txt'], stdin=ls.stdout, capture_output=True, encoding='utf8')
print(tee.stdout)