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

วิธีรันไฟล์ Python ใน Python Shell

เพื่อรันไฟล์ Python ใน Python shell สามารถใช้ execfile (Python 2) หรือ exec ได้

ตัวอย่าง

สมมติมี my_script.py ที่มีโค้ด:

print("Greetings from my_script")

ใน Python shell:

>>> execfile('my_script.py')
Greetings from my_script

หรือใช้ exec (ทำงานใน Python 2 และ 3):

>>> exec(open("my_script.py").read())
Greetings from my_script

หมายเหตุ: execfile ถูกลบใน Python 3 ควรใช้ exec(open(...).read()) แทน