Python3 turns string into executable command

Execution of python string type code

  • eval()Execute string type code. And return the final result
  • exec()Execute string type code
  • compile()Encode string type code. Code objects can be execexecuted or eval()evaluated through statements
#输入:8+9
s1 = input("请输入a+b:")  
# 17 可以动态的执行代码. 代码必须有返回值
print(eval(s1))  

image.png

s2 = "for i in range(5): print(i)"

# exec 执行代码不返回任何内容
a = exec(s2) 
# 0
# 1
# 2
# 3
# 4
print(a)  
#None

image.png


eval() turns a string into an executable command

Reference: https://blog.csdn.net/weixin_34128237/article/details/91933587

Python3Usage eval()methods can be 字符串turned into 系统执行的命令.
eval()Functions can be used to run string expressions.

For example:

# eval将字符串作为代码执行
n = input('请输入一个1000--9999的整数')
s = eval(f'{
      
      n[0]}+{
      
      n[1]}+{
      
      n[2]}+{
      
      n[3]}')
print(f'{
      
      n}每一位的数字之和为:{
      
      s}')

Insert image description here


exec() dynamically executes code

exec()Functions can execute more complex string code.

Reference: https://www.runoob.com/python/python-func-exec.html

exec("""
def func():
    print(" 我是周杰伦")
""")

# 打印结果:我是周杰伦
func()

image.png


compile() compiles a string into bytecode

https://www.runoob.com/python/python-func-compile.html

compile()Function compiles a string into byte code.

code1 = "for i in range(3): print(i)"
# compile并不会执行你的代码.只是编译
com = compile(code1, "", mode="exec")
# 执行编译的结果
exec(com)

image.png

code2 = "5+6+7"
com2 = compile(code2, "", mode="eval")
print(eval(com2))

image.png

code3 = "name = input('请输入你的名字:')"  # 输入:hello
com3 = compile(code3, "", mode="single")
exec(com3)
print(name)

image.png

Guess you like

Origin blog.csdn.net/omaidb/article/details/131962502
Recommended