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

Python sys Module คืออะไร และการใช้งานพื้นฐาน

บทนำ

โมดูล sys ใน Python ให้ข้อมูลเกี่ยวกับ Python interpreter และอนุญาตให้เข้าถึงค่าคงที่ ฟังก์ชัน และเมธอดต่างๆ ของ interpreter

การเริ่มต้นใช้งาน

sys มาพร้อมกับ Python ไม่ต้องติดตั้งเพิ่ม ใช้คำสั่ง import sys

ฟังก์ชันหลักและตัวอย่าง

1. sys.argv - อ่าน аргументบรรทัดคำสั่ง

# example.py
import sys
print("You entered:", sys.argv[1], sys.argv[2])

รัน: python example.py Hello World → Output: Hello World

หมายเหตุ: sys.argv[0] คือชื่อสคริปต์ เริ่มอ่าน argument จาก index 1

2. sys.exit() - หยุดโปรแกรมทันที

import sys
print("Hello there!")
sys.exit()
print("This line is not executed")

3. sys.version - ตรวจสอบเวอร์ชัน Python

import sys
print("You are currently using Python version", sys.version)

4. sys.path - ตำแหน่งโมดูลที่ติดตั้ง

import sys
sys.path

5. sys.stdin - อ่าน input จากผู้ใช้

import sys
data = sys.stdin.readline()
print("You have entered -> " + data)

สรุป

sys module ให้เครื่องมือพื้นฐานสำหรับ script ที่รันบน command line: อ่าน arguments, อ่าน stdin, หยุดโปรแกรม, ตรวจสอบ environment

เอกสารเต็ม: https://docs.python.org/3/library/sys.html