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

วิธีเข้าถึง Command Line Arguments ใน Python

Command line คือที่ที่พิมพ์คำสั่งให้ระบบปฏิบัติการ รันสคริปต์ Python โดยพิมพ์ชื่อไฟล์หลังคำสั่ง python

C:\users\acer> python test.py

หากต้องการส่งข้อมูลให้สคริปต์ ให้พิมพ์ต่อท้ายชื่อไฟล์ คั่นด้วย space เรียกว่า command line arguments

ตัวอย่าง

C:\users\acer> python test.py Hello TutorialsPoint

ค่าเหล่านี้จะถูกเก็บใน list sys.argv (โมดูล sys):

sys.argv = ['test.py', 'Hello', 'TutorialsPoint']

ในโปรแกรมเข้าถึงได้โดย:

import sys
print("first command line argument:", sys.argv[1])
print("second command line argument:", sys.argv[2])