[Tutor] What am I missing here?

Dennis Lee Bieber wlfraed at ix.netcom.com
Sun Feb 13 12:37:34 EST 2022


On Sun, 13 Feb 2022 12:17:22 +0000, Nathan Smith <nathan-tech at hotmail.com>
declaimed the following:

>
>On a side note of this not being a *complete* bust, I could do a 
>separate program for running the python interactive shell by wrapping 
>something around eval, right?
>
>Eval can be dangerous because you can literally execute anything but, in 
>the case of a shell wrapper, that's kind of the point because it's the 
>same as running the python command anyway?
>

	Ugh... (Personal impression -- you also would have to manage the
"environment": global and local namespaces, to avoid having the "run task"
fill up your "shell" process with junk... or even change stuff if variable
names are the same)

>
>In that light though I have a new question. How would I go about running 
>something that was multiple lines?
>

	Did you look at exec()? Same problem with environment management but
works with "suites" of statements (think the >>> to ... change over in the
interactive Python console when entering an "if" statement, or similar).
https://docs.python.org/3/library/functions.html#eval
https://docs.python.org/3/library/functions.html#exec

>It's a bit of reinventing the wheel but if the user enters:
>
>for x in range(10):
>
>  print(x)
>
>
>How would I hand that off to eval? Putting:
>
>eval("for x in range(10): \n print(x)") throws me a syntax error.
>

	eval() works with EXPRESSIONS -- basically, anything that can be on the
right-hand side of an =

>>> while True:
...   expr = input("Enter expression to be evaluated> ")
...   resl = eval(expr)
...   print("Result:\t%s" % resl)
...
Enter expression to be evaluated> 3 + 234
Result: 237
Enter expression to be evaluated> 3 + 234 / 123
Result: 4.902439024390244
Enter expression to be evaluated> Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
EOFError
>>>

	exec(), as mentioned, works with statement (suites), not expressions,
and returns None (so if you need to extract computed values they should be
in the globals or locals dictionaries that are mutatable).

	Unfortunately, that does mean you'll need complete statement/suites --
you can't just feed one line at a time to it. (I'm not going to attempt a
demo). Which could mean having to implement (or invoke) the Python parser
and somehow tracking when it reports it is back to the top-level of
indentation -- then passing the code block to exec().



-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/



More information about the Tutor mailing list