Python:如何判断一个字符串代表一个语句还是一个表达式?
我需要根据输入字符串“s”调用 exec() 或 eval()
我想打印结果
如果“s”是一个表达式,在调用 eval() 后,如果结果不是 None如果“s”是, 一条语句然后简单地执行()。如果该语句碰巧打印出一些东西,那就这样吧。
s = "1 == 2" # user input # --- try: v = eval(s) print "v->", v except: print "eval failed!" # --- try: exec(s) except: print "exec failed!"
例如,“s”可以是:
s = "print 123"
在这种情况下,应使用 exec()。
当然,我不想先尝试 eval() ,如果失败则调用 exec()
I need to either call exec() or eval() based on an input string "s"
If "s" was an expression, after calling eval() I want to print the result if the result was not None
If "s" was a statement then simply exec(). If the statement happens to print something then so be it.
s = "1 == 2" # user input # --- try: v = eval(s) print "v->", v except: print "eval failed!" # --- try: exec(s) except: print "exec failed!"
For example, "s" can be:
s = "print 123"
And in that case, exec() should be used.
Ofcourse, I don't want to try first eval() and if it fails call exec()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试将其
编译
为表达式。如果失败,那么它一定是一个声明(或者只是无效)。Try to
compile
it as an expression. If it fails then it must be a statement (or just invalid).听起来您似乎希望用户能够在脚本中与 Python 解释器进行交互。 Python 通过调用
code.interact
实现这一点:运行脚本:
解释器知道脚本中设置的局部变量:
用户还可以更改局部变量的值:
按 Ctrl-d将控制流返回给脚本。
It sort of sounds like you'd like the user to be able to interact with a Python interpreter from within your script. Python makes it possible through a call to
code.interact
:Running the script:
The intepreter is aware of local variables set in the script:
The user can also change the value of local variables:
Pressing Ctrl-d returns flow of control to the script.