Python Forum
setting STDOUT and/or STDERR
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
setting STDOUT and/or STDERR
#8
(Dec-07-2023, 06:32 PM)Skaperen Wrote: i want to have this more integrated so that the redirection is done by the script itself and minimize the number of files
The more pythonic way could be to use @DeaD_EyE 's suggestion plus subprocess.check_output() or Popen.communicate(). Here is a 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)

    # run some command which creates output
    data = sp.check_output(['date'], stderr=sp.STDOUT, encoding='utf8')
    print(data, end='')

with Path("/tmp/bigscript.log").open("w") as ofile:
    with redirect_stdout(ofile), redirect_stderr(ofile):
        main()
Output:
λ cat /tmp/bigscript.log ['paillasse/pf/myscript.py'] ven. 08 déc. 2023 09:38:16 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,798 Nov-01-2019, 07:06 AM
Last Post: Gribouillis
  capture stdout from child processes Skaperen 0 3,362 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