简体   繁体   English

在python中运行包含python代码的字符串。

[英]run a string containing python code in python.

I have a string containing some if/else statements, for example: 我有一个包含一些if / else语句的字符串,例如:

self.y = 10

x = "if 1 > self.y: DO-Something else: Do-something-else"

is it possible to run this code while the program is opperating. 程序运行时是否可以运行此代码。 (pseudocode explination) (伪代码说明)

x = "if 1 > self.y: DO-Something else: Do-something-else"

runprogram(x)

Thanks! 谢谢!

As mentioned in the comments, you can use exec (eval would do too, in some situations). 如评论中所述,您可以使用exec(在某些情况下eval也会这样做)。

But you need to be very careful, especially if the code to be evaluated (or executed) will be input by the users. 但是您需要非常小心,尤其是要评估(或执行)的代码将由用户输入时。

use exec to execute your code in string. 使用exec以字符串形式执行代码。

But use exec with care :) 但是请谨慎使用exec :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM