โหมดโต้ตอบ (Interactive Mode) ของ Python ทำงานหลักการ REPL (Read - Evaluate - Print - Loop) โมดูล code ใน Standard Library ของ Python มีคลาสและฟังก์ชันสะดวกสำหรับตั้งค่าสภาพแวดล้อม REPL จากในสคริปต์ Python
คลาสสองตัวในโมดูล code
- InteractiveInterpreter: จัดการการแยกวิเคราะห์ (parsing) และสถานะของ Interpreter (namespace ของผู้ใช้)
- InteractiveConsole: ลเลียนทำงานของ Python Interpreter แบบโต้ตอบอย่างใกล้ชิด
ฟังก์ชันสะดวกสองฟังก์ชัน
- interact(): ฟังก์ชันสะดวกสำหรับรัน Read-Eval-Print Loop
- compile_command(): ใช้สำหรับโปรแกรมที่ต้องการเลียนแบบ Main Loop ของ Python Interpreter (REPL)
เมธอดของ InteractiveInterpreter
- runsource(): คอมไพล์และรันซอร์สโค้ดใน Interpreter
- runcode(): รัน Code Object
เมธอดของ InteractiveConsole (Subclass ของ InteractiveInterpreter)
- interact(): ลเลียน Interactive Python Console อย่างใกล้ชิด
- push(): ส่งบรรทัดซอร์สโค้ดไปยัง Interpreter
- resetbuffer(): ลบซอร์สโค้ดที่ยังไม่ได้จัดการออกจาก Input Buffer
- raw_input(prompt=""): เขียน Prompt และอ่านบรรทัดหนึ่งจาก sys.stdin
ตัวอย่าง
import code
x = 10
y = 20
def add(x, y):
return x + y
print(add(x, y))
code.interact(local=locals())
print(x, y)
print(add(x, y))
ในโค้ดข้างต้น กำหนดตัวแปรสองตัวและส่งให้ฟังก์ชัน แล้วเรียก Interactive Console อาร์กิวเมนต์ local=locals() อนุญาตให้ใช้ Local Namespace เป็นค่าเริ่มต้นภายใน Interpreter Loop
หากคุณกำหนดค่าต่างๆ ให้ตัวแปรและออกจาก Console โดยกด Ctrl+D ค่าเหล่านั้นจะถูกส่งต่อให้ฟังก์ชัน
ผลลัพธ์
addition= 30 Python 3.6.6 |Anaconda custom (64-bit)| (default, Oct 9 2018, 12:34:16) [GCC 7.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> x=100 >>> y=200 >>> now exiting InteractiveConsole... 100 200 addition = 300