Python Forum
subprocess_run and stdout flux
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
subprocess_run and stdout flux
#1
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)
Reply
#2
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)
Reply
#3
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)
Axel_Erfurt likes this post
« We can solve any problem by introducing an extra level of indirection »
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Failing to iterate over captured StdOut tester_V 4 1,559 Jul-12-2024, 03:36 PM
Last Post: deanhystad
  [subprocess] Why stdout sent to stderr? Winfried 3 2,103 Jan-26-2024, 07:26 PM
Last Post: snippsat
  Performance options for sys.stdout.writelines dgrunwal 11 6,159 Aug-23-2022, 10:32 PM
Last Post: Pedroski55
  changing stdout and stderr Skaperen 4 4,056 Dec-02-2020, 08:58 PM
Last Post: Skaperen
  Get stdout of a running process yok0 0 4,405 Aug-20-2020, 10:12 AM
Last Post: yok0
  will with sys.stdout as f: close sys.stdout? Skaperen 9 7,076 Nov-03-2019, 07:57 AM
Last Post: Gribouillis
  Add stdout to text file maxtimbo 3 4,031 Feb-05-2019, 12:53 AM
Last Post: maxtimbo
  flux management chris_thibault 3 3,696 Sep-10-2018, 10:23 AM
Last Post: chris_thibault
  stdout buffering Skaperen 5 6,299 Jun-12-2018, 06:14 AM
Last Post: Skaperen
  stdout Skaperen 0 3,127 Mar-19-2018, 01:23 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020