0

I have this code:

line = input("Line of code: ")
output = exec(line)

Naturally it doesn't work because if you write print("Hello World") it only prints "Hello World" and the output variable will have None value. So, in PHP I could use the output buffering in this way:

<?php
ob_start();
echo "Hello World";
output = ob_get_clean();
?>

Is there an equivalent function or a similar way in Python? This is exactly what I need. Thanks in advance.

  • 3
    This seems like a [XY problem](https://xyproblem.info/). What you are describing does not make much sense to do in Python as it does in PHP. It would be better to describe *why* you came to the conclusion that you need such a function. What else have you tried that did not work, what are you trying to achieve? – Marco Bonelli Feb 07 '22 at 20:08
  • further explain your end goal. I do not know PHP, but I can give the python version if I understand what you are looking for... – Eli Harold Feb 07 '22 at 20:08
  • What is the intended value for `output`? – Eli Harold Feb 07 '22 at 20:10
  • Is this what you are looking for? https://stackoverflow.com/questions/35779023/get-text-contents-of-what-has-been-printed-python – sudden_appearance Feb 07 '22 at 20:14
  • @EliHarold I need to save the result of a `print()` in a variable. In PHP there's a thing called Output Buffering that saves the result of a block of code in a variable. –  Feb 07 '22 at 20:17
  • I see, that does not make much sense in python. Why not save the values before you print them? – Eli Harold Feb 07 '22 at 20:21
  • 1
    But @sudden_appearance seems to have linked your answer. – Eli Harold Feb 07 '22 at 20:23
  • 1
    There are two different concepts going on here, and I think it's making the question more confusing. The PHP snippet doesn't reflect the fact that you're trying to [`eval`](https://www.php.net/manual/en/function.eval.php)uate arbitrary code. Ultimately (I think) what you're looking to do is read a line of code from user input, and then capture the **result** of that code. – iainn Feb 07 '22 at 20:23
  • @SimCop07 if what iainn said is true then `eval()` is a function that can "run" code from a string. – Eli Harold Feb 07 '22 at 20:24
  • No, because if I want to run `var = value` I can only use `exec()` –  Feb 07 '22 at 20:42

1 Answers1

0

You could patch print to write into a temporary buffer:

from io import StringIO

#line = input("Line of code: ")
line = 'print("Hello World")'


# patch print. All following print statements are writing into in-memory text buffer!
out = StringIO('')

# Keep reference to old print function
_print = print

# overwrite print, in order to write into StringIO
print = lambda x: _print(x, file=out)
print("Before.")
exec(line)
print("After.")
print = _print # Switch back to original version
print(out.getvalue())

Out:

Before.
Hello World
After.
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47