Python Forum
setting STDOUT and/or STDERR
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
setting STDOUT and/or STDERR
#6
(Dec-07-2023, 04:56 AM)DeaD_EyE Wrote: It could work, if you set stderr and stdout to subprocess.PIPE.
I tried it but it doesn't work. Here is my script
# myscript.py
from contextlib import redirect_stdout, redirect_stderr
from pathlib import Path
import subprocess as sp
import sys


def main():
    # print our args
    print(sys.argv)
    sys.stdout.flush()

    # run some command which creates output
    sp.run(["date"], stdout=sp.PIPE, stderr=sp.PIPE) # OUTPUT IS LOST


with Path("/tmp/bigscript.log").open("w") as ofile:
    with redirect_stdout(ofile), redirect_stderr(ofile):
        main()
Output:
λ python paillasse/pf/myscript.py λ cat /tmp/bigscript.log ['paillasse/pf/myscript.py'] λ
I don't know where the output of sp.run(["date"], stdout=sp.PIPE, stderr=sp.PIPE) was sent.

On the other hand IT WORKS if I call instead explicitly
    sp.run(["date"], stdout=sys.stdout, stderr=sys.stderr)
This could be the pythonic way to go, but I don't think I could do this and redirect to an abstract file object without fileno, in order to make a tee for example.
« 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