Topics:
1. SYS Modules
2. Using Sys argv
3. Sys argv - Guessing Game
1. SYS Modules
>>Return to Menu
The sys module provides functions and variables used to manipulate different parts of the Python runtime environment.
sys.argv
sys.argv returns a list of command line arguments passed to a Python script. The item at index 0 in this list is always the name of the script. The rest of the arguments are stored at the subsequent indices.
import sys
print("You entered: ",sys.argv[1], sys.argv[2], sys.argv[3])
C:\python36> python test.py Python C# Java
>>>You entered: Python C# Java
sys.exit
This causes the script to exit back to either the Python console or the command prompt. This is generally used to safely exit from the program in case of generation of an exception.
import sys
sys.exit
sys.maxsize
Returns the largest integer a variable can take.
import sys
sys.maxsize
>>>9223372036854775807
sys.path
This is an environment variable that is a search path for all Python modules.
import sys
sys.path
>>>['', 'C:\\python36\\Lib\\idlelib', 'C:\\python36\\python36.zip',
'C:\\python36\\DLLs', 'C:\\python36\\lib', 'C:\\python36',
'C:\\Users\\acer\\AppData\\Roaming\\Python\\Python36\\site-packages',
'C:\\python36\\lib\\site-packages']
sys.version
This attribute displays a string containing the version number of the current Python interpreter.
import sys
sys.version
>>>'3.7.0 (v3.7.0:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)]'
sys.executable
Prints the absolute path of the python interpreter binary.
import sys
sys.executable
>>>'/usr/bin/python3'
sys.platform
Prints the os platform type. This function will be very useful when you run your program as a platform dependent.
import sys
sys.platform
>>>'linux'
2. Using Sys argv
>>Return to Menu
import sys
first = sys.argv[1]
second = sys.argv[2]
print(f"Welcome, {first} {second}")
3. Sys argv - Guessing Game
>>Return to Menu
from random import randint
import sys
answer = randint(int(sys.argv[1]), int(sys.argv[2]))
while True:
try:
guess = int(input(f'guess a number {sys.argv[1]}~{sys.argv[2]}: '))
if 0 < guess < 11:
if guess == answer:
print('you are a genius!')
break
else:
print('hey bozo, I said 1~10')
except ValueError:
print('please enter a number')
continue
#End
Hope you enjoyed this! :) Follow me for more contents...
Get in Touch:
ifeanyiomeata.com
contact@ifeanyiomeata.com
Youtube: youtube.com/c/IfeanyiOmeata
Linkedin: linkedin.com/in/omeatai
Twitter: twitter.com/iomeata
Github: github.com/omeatai
Stackoverflow: stackoverflow.com/users/2689166/omeatai
Hashnode: hashnode.com/@omeatai
Medium: medium.com/@omeatai
© 2022