19 sys module in python
'''
1. Using sys module we can do system related operation.
'''
import sys
print(sys.version)
## to append path
#sys.path.append(r'C:\\Users\\sriram\\Desktop\\akr')
## To exit from execution
print(' \n Before exit')
sys.exit()
print(' \n After exit')
-------------Input and Output using sys
The sys modules provide variables for better control over input or output.
We can even redirect the input and output to other devices.
This can be done using three variables –
1.stdin
2.stdout
3.stderr
----stdin---: It can be used to get input from the command line directly.
It used is for standard input.
It internally calls the input() method.
It, also, automatically adds ‘\n’ after each sentence.
import sys
for line in sys.stdin:
if 'q' == line.rstrip():
break
print(f'Input : {line}')
print("Exit")
--------stdout-------: A built-in file object that is to
the interpreter’s standard output stream in Python.
import sys
sys.stdout.write('umamahesh')
---------stderr------------: Whenever an exception occurs in Python
it is written to sys.stderr.
import sys
def print_to_stderr(*a):
# Here a is the array holding the objects
# passed as the argument of the function
print(*a, file = sys.stderr)
print_to_stderr("Hello World")
Exiting the Program
sys.exit([arg]) can be used to exit the program
import sys
age = 17
if age < 18:
# exits the program
sys.exit("Age less than 18")
else:
print("Age is not less than 18")
Working with Modules
sys.path is a built-in variable within the sys module
that returns the list of directories that
the interpreter will search for the required module.
import sys
print(sys.path)
## To get command line arguments
#first_com_arg = sys.argv[1]
#print(' first_com_arg is :', first_com_arg)
Comments
Post a Comment