Unit Iii
Unit Iii
The sys module in Python provides various functions and variables that are
used to manipulate different parts of the Python runtime environment.
It allows operating on the interpreter as it provides access to the variables and
functions that interact strongly with the interpreter
print(sys.version)
OUTPUT
(main, Nov 20 2023, 15:14:05): This part provides additional information about the
Python build.
[GCC 11.4.0]: This segment provides information about the compiler used to build Python
and its version.
GCC: This indicates the GNU Compiler Collection, which is a compiler system used for
building many Unix-like operating systems.
11.4.0: This is the version of the GCC compiler used for building Python.
import sys
for line in sys.stdin:
if 'q' == line.rstrip():
break
print(f'Input : {line}')
print("Exit")
Output:
import sys
sys.stdout.write('SRM')
Output
SRM
Python3
import sys
def print_to_stderr(*a):
print_to_stderr("Hello World")
Output:
Command Line Arguments
Command-line arguments are those which are passed during the calling of the program
along with the calling statement. To achieve this using the sys module, the sys module
provides a variable called 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.
Here is a Python script (test.py) consuming two arguments from the command line.
import sys
print("You entered: ",sys.argv[1], sys.argv[2], sys.argv[3])
Example: Consider a program for adding numbers and the numbers are passed along
with the calling statement.
This code calculates the sum of the command-line arguments passed to the Python
script. It imports the sys module to access the command-line arguments and then
iterates over the arguments, converting each one to an integer and adding it to a running
total. Finally, it prints the total sum of the arguments
import sys
n = len(sys.argv)
Sum = 0
Sum += int(sys.argv[i])
print("\n\nResult:", Sum)
Output:
Exiting the Program
sys.exit([arg]) can be used to exit the program. The optional argument arg can be an
integer giving the exit or another type of object. If it is an integer, zero is considered
“successful termination”.
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.
Note: A string can also be passed to the sys.exit() method.
Example:
This code checks if the age is less than 18. If it is, it exits the program with a
message “Age less than 18”. Otherwise, it prints the message “Age is not less than
18”. The sys.exit() function takes an optional message as an argument, which is
displayed when the program exits.
import sys
age = 17
if age < 18:
sys.exit("Age less than 18")
else:
print("Age is not less than 18")
Output:
An exception has occurred, use %tb to see the full traceback.
import sys
print(sys.path)
Output:
sys.modules return the name of the Python modules that the current shell has
imported.
Example:
This code will print a dictionary of all the modules that have been imported by the
current Python interpreter. The dictionary keys are the module names, and the
dictionary values are the module objects.
import sys
print(sys.modules)
Output:
Reference Count
sys.getrefcount() method is used to get the reference count for any given object. This
value is used by Python as when this value becomes 0, the memory for that particular
value is deleted.
Example:
This code prints the reference count of the object a. The reference count of an object is
the number of times it is referenced by other objects. An object is garbage collected
when its reference count reaches 0, meaning that it is no longer referenced by any other
objects
import sys
a = 'Geeks'
print(sys.getrefcount(a))
Output
Sys.maxsize
The sys.maxsize attribute in Python returns the maximum size of integers that can be
represented on your platform. This value varies depending on whether you are using a
32-bit or 64-bit platform.
import sys
sys.maxsize
Output
9223372036854775807
sys.getsizeof():
After using this function, the size of an object in bytes is returned. Any object can be used
as an object.
import sys
i=3
print(sys.getsizeof(i))
Output
28
As it is clear from the above example that the sys.getsize() is returning the size of the
object created, that is, "i" here with integer value 3.
sys.getrecursionlimit():
import sys
Max_limit = sys.getrecursionlimit()
print(Max_limit)
Output
1000
Function Description
os.walk() method of the OS module can be used for listing out all the directories. This
method basically generates the file names in the directory tree either top-down or
bottom-up. For each directory in the tree rooted at directory top (including top itself),
it yields a 3-tuple (dirpath, dirnames, filenames).
Parameters:
top: Starting directory for os.walk().
topdown: If this optional argument is True then the directories are scanned from top-
down otherwise from bottom-up. This is True by default.
onerror: It is a function that handles errors that may occur.
followlinks: This visits directories pointed to by symlinks, if set to True.
Return Type: For each directory in the tree rooted at directory top (including top itself),
it yields a 3-tuple (dirpath, dirnames, filenames).
We want to list out all the subdirectories and file inside the directory Tree. Below is
the implementation.
import os
Output:
The above code can be shortened using List Comprehension which is a more Pythonic
way. Below is the implementation.
import os
Output:
Queue is a linear data structure that stores items in a First-In/First Out(FIFO) manner.
In queue, the data element that is inserted first will be removed first.
1. Enqueue: It adds an item to the queue. If the queue is full, then it is said to be
an Overflow condition.
2. Dequeue: It removes an item from the queue. The items are popped in the same
order in which they are pushed. If the queue is empty, then it is said to be an
Underflow condition.
1. list
2. collections.deque
3. queue.Queue
Example:
queue = []
queue.append('a')
queue.append('b')
queue.append('c')
print("Initial queue")
print(queue)
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
print(queue)
Implementation using collections.deque
Queue in Python can be implemented using deque class from the collections module.
Deque is preferred over list in the cases where we need quicker append and pop
operations from both the ends of container
Instead of enqueue and deque, append() and popleft() functions are used.
The code uses a deque from the collections module to represent a queue.
Example:
q = deque()
q.append('a')
q.append('b')
q.append('c')
print("Initial queue")
print(q)
print(q.popleft())
print(q.popleft())
print(q.popleft())
Example:
Multithreading in Python
There are two ways in which we can create a thread in python. They are as follows:
Thread modules
It is started with Python 3, designated as obsolete, and can only be accessed with _thread
that supports backward compatibility.
Syntax:
Threading Modules
Methods Description
start() -A start() method is used to initiate the activity of a thread. And it calls only once
for each thread so that the execution of the thread can begin.
run() -A run() method is used to define a thread's activity and can be overridden by a
class that extends the threads class.
join()- A join() method is used to block the execution of another code until the thread
terminates.
Follow the given below steps to implement the threading module in Python
Multithreading:
Syntax:
1. import threading
A threading module is made up of a Thread class, which is instantiated to create a Python
thread.
2. Declaration of the thread parameters: It contains the target function, argument, and
kwargs as the parameter in the Thread() class.
o Args: It defines the arguments that are passed to the target function name.
For example:
1. import threading
2. def print_hello(n):
In the above code, we invoked the print_hello() function as the target parameter. The
print_hello() contains one parameter n, which passed to the args parameter.
3. Start a new thread: To start a thread in Python multithreading, call the thread class's
object. The start() method can be called once for each thread object; otherwise, it throws
an exception error.
Syntax:
1. t1.start()
2. t2.start()
4. Join method: It is a join() method used in the thread class to halt the main thread's
execution and waits till the complete execution of the thread object. When the thread
object is completed, it starts the execution of the main thread in Python.
Joinmethod.py
1. import threading
2. def print_hello(n):
5. T1.start()
6. T1.join()
7. Print("Thank you")
Output:
Thank you
The join() method stops the main thread from running when the above program is run
and waits until the thread t1 has finished running. The main thread begins its execution
once the t1 has completed successfully
class Demo:
def display(self):
for i in range(6):
print("Child Thread")
obj=Demo()
t=Thread(target=obj.display)
t.start()
for i in range(6):
print("Main Thread")
We can create a thread by predefined Thread class. Here our class should inherit Thread
predefined class in python. Predefined Thread class contains run() method. In our child
class we need to override the run() method with our required functionality. Whenever
we call start() method then automatically run() method will be executed and performs
our job.
class MyThread(Thread):
def run(self):
for i in range(6):
print("Child Thread")
t=MyThread()
t.start()
for i in range(6):
print("Main Thread")
Every thread in python has some name associated with it. It might be the default name
generated by Python or a name which can also be customized.
current_thread().setName("MyThread")
Output:
As already stated, current_thread() will return an object to the current thread. By the
default the program runs on Main Thread.
For every thread internally, a unique identification number will be available. We can
access this by using implicit variable “ident”.
def m():
print("Child Thread")
t=Thread(target=m)
t.start()
2. enumerate()
3. isAlive()
4. join()
5. join(seconds)
active_count() method:
import time
def display():
print(current_thread().getName(), "...started")
time.sleep(3)
print(current_thread().getName(), "...ended")
t1=Thread(target=display, name="ChildThread1")
t2=Thread(target=display, name="ChildThread2")
t3=Thread(target=display, name="ChildThread3")
t1.start()
t2.start()
t3.start()
enumerate() function:
This function returns a list of the objects of all active threads currently running.
import time
def display():
print(current_thread().getName(), "...started")
time.sleep(3)
print(current_thread().getName(), "...ended")
t1=Thread(target=display, name="ChildThread1")
t2=Thread(target=display, name="ChildThread2")
t3=Thread(target=display, name="ChildThread3")
t1.start()
t2.start()
t3.start()
l=enumerate()
for t in l:
time.sleep(5)
l=enumerate()
for t in l:
isAlive() method:
import time
def display():
print(current_thread().getName(), "...started")
time.sleep(3)
print(current_thread().getName(), "...ended")
t1=Thread(target=display, name="ChildThread1")
t2=Thread(target=display, name="ChildThread2")
t1.start()
t2.start()
time.sleep(5)
join() method:
If we want a particular thread to wait for another thread to complete, then we can use
join() method.
import time
def display():
for i in range(5):
print("First Thread")
t=Thread(target=display, name="ChildThread")
t.start()
for i in range(5):
print("Second Thread")
Output:
Here the main thread will wait until the child thread gets completed.
join(seconds) method:
The join method above can also be used by passing the argument ,in the seconds, time
period also. In this case thread will wait only specified amount of time.
Program: join(seconds) method in Python (demo13.py)
import time
def display():
for i in range(5):
print("First Thread")
time.sleep(2)
t=Thread(target=display, name="ChildThread")
t.start()
for i in range(5):
print("Second Thread")
Daemon threads:
When a program is running there are some process, related to the program, that will be
running in the background supporting the program execution. Such threads or processes
which are running in the background are called Daemon Threads. The main objective of
Daemon Threads is to provide support for Non-Daemon Threads (like main thread)
Whenever Main Thread runs with low memory, immediately PVM runs Garbage Collector
to destroy useless objects and to provide free memory, so that Main Thread can continue
its execution without having any memory problems.
We can check whether the thread is Daemon or not, by using isDaemon() method of
Thread class and also by using daemon property.
print(current_thread().isDaemon())
print(current_thread().daemon)
We can change Daemon nature by using the setDaemon() method of Thread class. In this
perspective, let’s know some points.
def display():
print("Child Thread")
t=Thread(target=display)
t.start()
t.setDaemon(True)
Output:
import time
def display():
for i in range(5):
print("Child Thread")
time.sleep(2)
t=Thread(target=display)
t.setDaemon(True)
t.start()
time.sleep(5)