[Python] วิธีการเขียน code ส่งค่า Arguments ผ่านทาง Command-Line
Python มีคลาสที่ชื่อว่า getotp สำหรับช่วยในการส่งค่า options และ arguments เข้าไปในโปรแกรม แล้วนำค่าต่างๆ ที่ได้ไปใช้ในโปรแกรมต่อไป โดยมีรูปแบบดังนี้
getopt.getopt(arg, options[, long_options])
arg คือ arguments ที่ต้องการส่งค่าเข้าไปในโปรแกรม
options คือ options ที่ต้องการสั่งให้โปรแกรมทำงาน โดยแยกแต่ละ option ด้วยเครื่องหมายโคลอน (:) เช่น h:i:o:
long_options คือ เป็นค่าที่มีหรือไม่มีก็ได้ ในกรณีที่มีค่าจะต้องเป็นตัวแปร ชนิด List และต้องเป็น option แบบยาว โดยค่าในแต่ละ option จะต้องใช้เครื่องหมายเท่ากับ (=) ในการกำหนด เช่น [“inputfile=”,”outputfile”]
สามารถดู video และ source code ตามด้านล่าง
พูดคุยแลกเปลี่ยนได้ที่ Facebook Fanpage
import sys, getopt | |
def main(argv): | |
inputfile = '' | |
outputfile = '' | |
try: | |
opts, args = getopt.getopt(argv, "h:i:o:",["ifile=","ofile="]) | |
except getopt.GetoptError: | |
print('GetoptError test.py -i <inputfile> -o <outputfile>') | |
sys.exit(2) | |
for opt, arg in opts: | |
if opt == '-h': | |
print('test.py -i <inputfile> -o <outputfile>') | |
sys.exit() | |
elif opt in ('-i', '--ifile'): | |
inputfile = arg | |
elif opt in ('-o', '--ofile'): | |
outputfile = arg | |
print('input file is "', inputfile) | |
print('output file is "', outputfile) | |
if __name__ == "__main__": | |
main(sys.argv[1:]) |