Python Forum
setting STDOUT and/or STDERR
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
setting STDOUT and/or STDERR
#2
(Dec-05-2023, 07:10 AM)Skaperen Wrote: is this code good enough or is there a more expected (and pythonic) way to do this?
I think it is ok if you want to do this very specific thing, redirect every output of subprocesses to the file.

I would probably choose another way. First you can redirect the streams when the script is invoked, for example let the script be
# myscript.py
import subprocess as sp
import sys

# print our args
print(sys.argv)
sys.stdout.flush()

# run some command which creates output
sp.run(["date"])
It can be invoked at the console with a redirection
Output:
λ python paillasse/pf/myscript.py --spam eggs ham >/tmp/bigscript.log 2>&1 λ
Let us check the content of /tmp/bigscript.log
Output:
λ cat /tmp/bigscript.log ['paillasse/pf/myscript.py', '--spam', 'eggs', 'ham'] mar. 05 déc. 2023 11:09:13 CET λ
If we don't want to redirect it at the console, we can interpose a driver script which does the redirection
# driver.py
from pathlib import Path
import subprocess as sp
import sys

myscript = Path(__file__).parent / "myscript.py"

with Path("/tmp/bigscript.log").open("w") as ofile:
    sp.run([sys.executable, myscript, *sys.argv[1:]], stdout=ofile, stderr=sp.STDOUT)
Let us invoke the driver
Output:
λ python paillasse/pf/driver.py --spam eggs ham λ
We now check the content of the output file
Output:
λ cat /tmp/bigscript.log ['/home/eric/Projets/Scratch/2023-01/paillasse/pf/myscript.py', '--spam', 'eggs', 'ham'] mar. 05 déc. 2023 11:11:43 CET λ
« We can solve any problem by introducing an extra level of indirection »
Reply


Messages In This Thread
setting STDOUT and/or STDERR - by Skaperen - Dec-05-2023, 07:10 AM
RE: setting STDOUT and/or STDERR - by Gribouillis - Dec-05-2023, 10:14 AM
RE: setting STDOUT and/or STDERR - by DeaD_EyE - Dec-05-2023, 01:06 PM
RE: setting STDOUT and/or STDERR - by Gribouillis - Dec-05-2023, 03:20 PM
RE: setting STDOUT and/or STDERR - by DeaD_EyE - Dec-07-2023, 04:56 AM
RE: setting STDOUT and/or STDERR - by Gribouillis - Dec-07-2023, 06:21 AM
RE: setting STDOUT and/or STDERR - by Skaperen - Dec-07-2023, 06:32 PM
RE: setting STDOUT and/or STDERR - by Gribouillis - Dec-08-2023, 08:38 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  combining stdout and stderr Skaperen 1 1,862 Nov-01-2019, 07:06 AM
Last Post: Gribouillis
  capture stdout from child processes Skaperen 0 3,458 Oct-30-2019, 12:11 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