หน้าเว็บ

วันอาทิตย์ที่ 9 มกราคม พ.ศ. 2554

วิธีทำให้ Python เรียก script อื่นทำงาน (execute external script)

ถ้าเรามี script ไฟล์ python (.py) อยู่ไฟล์นึง แล้วเราอยากให้ script ไฟล์ python อีกฝ่ายมาเรียกไฟล์แรกทำงาน(คล้ายๆการ include ใน php) ทำได้ดังนี้

สมมติว่ามีไฟล์ hello.py ซึ่งมีโค้ดดังนี้อยู่
print 'hello world'


คราวนี้ในไฟล์ที่สองชื่อ run.py จะเรียกใช้ hello.py

วิธีแรก
ในไฟล์ run.py ให้ใช้คำสั่ง execfile

...
execfile('hello.py')
...


กรณีแรกนี้คือสั่งเรียกไฟล์ python อื่น แต่ว่าถ้าเราต้องการเรียก script หรือ shell command ใดๆนอกจาก python ก็ทำได้เหมือนกัน โดยใช้วิธีที่สอง

วิธีที่สอง
ในไฟล์ run.py ให้ import โมดูลชื่อ os แล้วเรียก os.system(command) เช่น

import os
...
os.system('python hello.py')
...


หรือ

import os
...
os.system('cat hello.py | grep hello')
...


สำหรับวิธีแรกจะใช้ได้กับ python-2.x แต่ถ้าเป็น python-3.x ให้ใช้วิธีตาม link นี้แทน http://stackoverflow.com/questions/436198/what-is-an-alternative-to-execfile-in-python-3-0

ระบบที่ทดสอบ
Python: 2.6.6
OS: Ubunut 10.10

ที่มา
http://stackoverflow.com/questions/1027714/how-to-execute-a-file-within-the-python-interpreter

ไม่มีความคิดเห็น: