Python sys मॉड्यूल
In this page:
import sys
sys.argv
sys.exit(code)
sys.path
Command-Line Arguments
sys मॉड्यूल चल रहे Python interpreter के low-level details expose करता है, जो os के operating-system-level operations से अलग है।
sys.argv एक list है जिसमें index 0 हमेशा script का अपना filename होता है और बाकी entries वो arguments होते हैं जो command line पर उसके बाद टाइप किए गए थे।
उदाहरण: Command-Line Arguments
import sys
print(sys.argv[0])
Programs को सुरक्षित रूप से बंद करना
sys.exit() चल रहे program को तुरंत खत्म कर देता है, और चाहे तो एक integer exit code भी स्वीकार करता है जिसे दूसरे programs या shell scripts check कर सकते हैं -- रिवाज़ के अनुसार सफलता के लिए 0 और error होने पर कोई भी non-zero value।
यह अंदर से SystemExit exception raise करके काम करता है, इसलिए आस-पास के try/finally blocks अपना cleanup code फिर भी चला लेते हैं।
उदाहरण: Exiting Programs Safely
import sys
try:
print("Before exit")
sys.exit(0) # raises SystemExit with code 0
finally:
print("Cleanup still runs") # finally runs even though sys.exit() was called
System Paths की जाँच करना
sys.path उन directories की list है जिन्हें Python import statement resolve करते समय क्रम से खोजता है, जिसकी शुरुआत script की अपनी directory से होती है।
Runtime पर इस list में एक custom directory जोड़ना Python को उन modules ढूँढने का एक आम (हालांकि थोड़ा hacky) तरीका है जो normal installed-package locations से बाहर होते हैं।
उदाहरण: Inspecting System Paths
import sys
print(len(sys.path) > 0)
Standard Inputs और Outputs
sys.stdin, sys.stdout, और sys.stderr क्रमशः process के standard input, output, और error streams को represent करने वाले file-like objects हैं।
sys.stderr में सीधे लिखना उन error या diagnostic messages के लिए उपयोगी है जिन्हें आप program के normal stdout output से अलग रखना चाहते हैं, जो तब मायने रखता है जब output pipe या redirect किया जा रहा हो।
उदाहरण: Standard Inputs and Outputs
import sys
sys.stderr.write("This is an error message\n") # goes to the error stream, separate from stdout
print("This is normal output") # goes to stdout
Python Version की जानकारी
sys.version interpreter version और build details बताने वाली एक human-readable string देता है, जबकि sys.version_info वही जानकारी एक structured, comparable tuple जैसे (3, 11, 4) के रूप में देता है।
sys.version_info check करना version-specific code paths को guard करने का भरोसेमंद तरीका है, क्योंकि double-digit version numbers आने पर sys.version पर string comparison गलत क्रम में sort होने लगता है।
उदाहरण: Python Version Information
import sys
print(sys.version_info.major) # major version number as an int
print(sys.version_info >= (3, 0)) # tuple comparison works correctly, unlike comparing version strings
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: