Dec-05-2023, 10:14 AM
(This post was last modified: Dec-05-2023, 10:14 AM by Gribouillis.)
(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.logOutput:λ 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 fileOutput:λ 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 »