-1

Consider the following code:

code = input()
eval(code)

If I run it and type
> print(10)
It will get executed and print "10"

My question is when the code needs an indent, such as:

> for i in range(10):
>    print(i)

How can I receive this code with input() (notice that I have to keep the indent) so that I can use eval() to run it?

Inspi
  • 530
  • 1
  • 4
  • 19
Elicon
  • 206
  • 1
  • 11

2 Answers2

0

If i understand correctly you want to be able to get python code using input() with tabs included.

the post How to read multiple lines of raw input? tells us that we can get multiline input with

code = '\n'.join(iter(input, ''))

But after trying that myself I noticed that exec(code) didn't work because tabs were omitted from the input.

So here's a function that reads character directly and stops when it reads a given string
(here it's 2 newlines so you have to press ENTER twice to stop)

import sys

def input_until(sentinel):
    text = ""
    while not text.endswith(sentinel):
        text += sys.stdin.read(1)  # read 1 character from stdin
    # remove the stop string from the result
    return text[:-len(sentinel)]

code = input_until("\n\n")
exec(code)

I've tested it on https://replit.com/languages/python3 and it seems to work !

Inspi
  • 530
  • 1
  • 4
  • 19
-2

What's your use case here?

If you want to run the string in eval(), do you consider this?

new_string_name = "for i in range(10):\n    eval(a)"

or

new_string_name = "    eval()"

But if you don't want to follow the indentation rules (4 characters, no tabs), you can use

new_string_name = "for i in range(10):\n\teval(a)"

or

new_string_name = "\teval(a)"
S.B
  • 13,077
  • 10
  • 22
  • 49
NULL
  • 21
  • 4