#๐Ÿ”’ How Could I Turn That Last Printed Line Into A Variable?

14 messages ยท Page 1 of 1 (latest)

crude fractal
#

How could I turn the last printed line in the terminal into a variable? I know 99/100 times it is more practical to get the variable then print that, but I have a script that relies on printing random things and getting whatever the output of that is. Thank you in advance!

worthy nicheBOT
#

@crude fractal

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

crystal cedar
#

stuff printed is written to stdout... you could use contextlib.redirect_stdout to redirect all stdout to a file-like object (e.g. from io module).
or use a file-like object from io module and the use the file= keyword argument in all of your prints.

#

!e

import io
import contextlib

output = io.StringIO()
with contextlib.redirect_stdout(output):
    print('This is written to `output`')
    print(123, 'abc')
    print([1,2,3,4,5])

value = output.getvalue()
print(f'{value=}')
worthy nicheBOT
#

@crystal cedar :white_check_mark: Your 3.12 eval job has completed with return code 0.

value='This is written to `output`\n123 abc\n[1, 2, 3, 4, 5]\n'
crystal cedar
#
f = io.StringIO()
print('hello world', file=f)
``` that's the alternative, if you want it only on a single print
#

(though you could just store it in a variable to begin with)

static tulip
#

is the printing random things coming from another process?

crude fractal
crystal cedar
#

io

#

I use it in the snippet right afterwards

worthy nicheBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.