Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธี Execute String ที่มี Python Code ใน Python

exec() ใช้สำหรับ statement (หลายบรรทัดได้)

>> my_code = 'print "Hello World!"'
>>> exec(my_code)
Hello World!

eval() ใช้สำหรับ expression (คืนค่า)

>> my_expression = "5 + 3"
>>> eval(my_expression)
8

⚠️ คำเตือน: ใช้ระมัดระวังมาก อาจก่อให้เกิด security loopholes และ bugs ที่ล้มลึก