Python:如何判断一个字符串代表一个语句还是一个表达式?

发布于 2024-09-26 17:44:38 字数 435 浏览 4 评论 0原文

我需要根据输入字符串“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

三五鸿雁 2024-10-03 17:44:38

尝试将其编译为表达式。如果失败,那么它一定是一个声明(或者只是无效)。

isstatement= False
try:
    code= compile(s, '<stdin>', 'eval')
except SyntaxError:
    isstatement= True
    code= compile(s, '<stdin>', 'exec')

result= None
if isstatement:
    exec s
else:
    result= eval(s)

if result is not None:
    print result

Try to compile it as an expression. If it fails then it must be a statement (or just invalid).

isstatement= False
try:
    code= compile(s, '<stdin>', 'eval')
except SyntaxError:
    isstatement= True
    code= compile(s, '<stdin>', 'exec')

result= None
if isstatement:
    exec s
else:
    result= eval(s)

if result is not None:
    print result
可可 2024-10-03 17:44:38

听起来您似乎希望用户能够在脚本中与 Python 解释器进行交互。 Python 通过调用 code.interact 实现这一点:

import code    
x=3
code.interact(local=locals())
print(x)

运行脚本:

>>> 1==2
False
>>> print 123
123

解释器知道脚本中设置的局部变量:

>>> x
3

用户还可以更改局部变量的值:

>>> x=4

按 Ctrl-d将控制流返回给脚本。

>>> 
4        <-- The value of x has been changed.

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:

import code    
x=3
code.interact(local=locals())
print(x)

Running the script:

>>> 1==2
False
>>> print 123
123

The intepreter is aware of local variables set in the script:

>>> x
3

The user can also change the value of local variables:

>>> x=4

Pressing Ctrl-d returns flow of control to the script.

>>> 
4        <-- The value of x has been changed.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文