0% found this document useful (0 votes)
31 views30 pages

Unit Iii

The sys module in Python provides functions and variables to interact with the Python interpreter. It allows getting details like the Python version, reading input/output streams, getting command line arguments, and finding module paths. Functions like sys.exit() can exit the program and sys.getrefcount() returns the reference count of an object.

Uploaded by

susan babu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views30 pages

Unit Iii

The sys module in Python provides functions and variables to interact with the Python interpreter. It allows getting details like the Python version, reading input/output streams, getting command line arguments, and finding module paths. Functions like sys.exit() can exit the program and sys.getrefcount() returns the reference count of an object.

Uploaded by

susan babu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

SYS MODULE IN PYTHON

 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

Sys Module in Python


Python sys.version
sys.version is used which returns a string containing the version of Python
Interpreter with some additional information.
Eg:
import sys

print(sys.version)

OUTPUT

3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0]

3.10.12: This indicates the Python version.

(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.

Input and Output using Python 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 –
 stdin
 stdout
 stderr
Read from stdin in Python
stdin: It can be used to get input from the command line directly. It is used for
standard input. It internally calls the input() method. It, also, automatically adds ‘\n’
after each sentence.
Example:
This code reads lines from the standard input until the user enters ‘q’. For each line, it
prints “Input : ” followed by the line. Finally, it prints “Exit”.

import sys
for line in sys.stdin:
if 'q' == line.rstrip():
break
print(f'Input : {line}')

print("Exit")

Output:

Python sys.stdout Method


stdout: A built-in file object that is analogous to the interpreter’s standard output
stream in Python. stdout is used to display output directly to the screen console. Output
can be of any form, it can be output from a print statement, an expression statement,
and even a prompt direct for input. By default, streams are in text mode. In fact,
wherever a print function is called within the code, it is first written to sys.stdout and
then finally on to the screen.
Example:
This code will print the string “SRM” to the standard output. The sys.stdout object
represents the standard output stream, and the write() method writes the specified
string to the stream

import sys
sys.stdout.write('SRM')

Output
SRM

stderr function in Python


stderr: Whenever an exception occurs in Python it is written to sys.stderr.
Example:
This code will print the string “Hello World” to the standard error stream.
The sys.stderr object represents the standard error stream, and the print() function
writes the specified strings to the stream.

 Python3

import sys

def print_to_stderr(*a):

print(*a, file = sys.stderr)

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.

It’s main purpose are:


 It is a list of command-line arguments.
 len(sys.argv) provides the number of command-line arguments.

sys.argv[0] is the name of the current Python script.

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])

This script is executed from command line as follows:

>>> C:\python36> python test.py Python C# Java

You entered: Python C# Java

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)

print("Total arguments passed:", n)

print("\nName of Python script:", sys.argv[0])

print("\nArguments passed:", end = " ")

for i in range(1, n):

print(sys.argv[i], end = " ")

Sum = 0

for i in range(1, n):

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.

SystemExit: Age 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.
When a module is imported within a Python file, the interpreter first searches for the
specified module among its built-in modules. If not found it looks through the list of
directories defined by sys.path.
Note: sys.path is an ordinary list and can be manipulated.
Example 1: Listing out all the paths
This code will print the system paths that Python uses to search for modules.
The sys.path list contains the directories that Python will search for modules when it
imports them.

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():

This sys.getrecursionlimit() function is used to determine the interpreter's current


recursion limit or the maximum possible size or depth of the Python interpreter stack.
This limit protects any program from going into infinite recursion, which would
otherwise cause a program crash in Python.

import sys

Max_limit = sys.getrecursionlimit()
print(Max_limit)

Output

1000

More Functions in Python sys

Function Description

sys.setrecursionlimit() method is used


sys.setrecursionlimit() to set the maximum depth of the Python
interpreter stack to the required limit.

sys.getrecursionlimit() method is used


to find the current recursion limit of the
sys.getrecursionlimit() method
interpreter or to find the maximum
depth of the Python interpreter stack.

It is used for implementing debuggers,


profilers and coverage tools. This is
thread-specific and must register the
sys.settrace()
trace using threading.settrace(). On a
higher level, sys.settrace() registers the
traceback to the Python interpreter

sys.setswitchinterval() method is used


sys.setswitchinterval() method to set the interpreter’s thread switch
interval (in seconds).
Function Description

It fetches the largest value a variable of


sys.maxsize()
data type Py_ssize_t can store.

maxint/INT_MAX denotes the highest


sys.maxint value that can be represented by an
integer.

sys.getdefaultencoding() method is used


sys.getdefaultencoding() method to get the current default string encoding
used by the Unicode implementation.

Directory traversal tool

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).

dirpath: A string that is the path to the directory

dirnames: All the sub-directories from root.

filenames: All the files from root and directories.

Syntax: os.walk(top, topdown=True, onerror=None, followlinks=False)

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.

# Python program to list out


# all the sub-directories and files

import os

# List to store all


# directories
L = []

# Traversing through Test


for root, dirs, files in os.walk('Test'):

# Adding the empty directory to list


L.append((root, dirs, files))
print("List of all sub-directories and files:")
for i in L:
print(i)

Output:

List of all sub-directories and files:

('Test', ['B', 'C', 'D', 'A'], [])

('Test/B', [], [])

('Test/C', [], ['test2.txt'])

('Test/D', ['E'], [])

('Test/D/E', [], [])

('Test/A', ['A2', 'A1'], [])

('Test/A/A2', [], [])

('Test/A/A1', [], ['test1.txt'])

The above code can be shortened using List Comprehension which is a more Pythonic
way. Below is the implementation.

# Python program to list out


# all the sub-directories and files

import os

# List comprehension to enter


# all directories to list

L = [(root, dirs, files) for root, dirs, files, in os.walk('Test')]


print("List of all sub-directories and files:")
for i in L:
print(i)

Output:

List of all sub-directories and files:

('Test', ['B', 'C', 'D', 'A'], [])

('Test/B', [], [])

('Test/C', [], ['test2.txt'])

('Test/D', ['E'], [])

('Test/D/E', [], [])

('Test/A', ['A2', 'A1'], [])

('Test/A/A2', [], [])

('Test/A/A1', [], ['test1.txt'])

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.

Operations that can be performed on the queue are:

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.

3. Front: It gives the front item from the queue.

4. Rear: It gives the last item from the queue.


Implementation

Queue in Python can be implemented in the following ways:

1. list
2. collections.deque
3. queue.Queue

Implementation using list


List is a Python’s built-in data structure that can be used as a queue. Instead of
enqueue() and dequeue(), append() and pop() function is used. However, lists are
quite slow for this purpose because inserting or deleting an element at the beginning
requires shifting all of the other elements by one

Example:

queue = []

queue.append('a')

queue.append('b')

queue.append('c')

print("Initial queue")

print(queue)

print("\nElements dequeued from queue")

print(queue.pop(0))

print(queue.pop(0))

print(queue.pop(0))

print("\nQueue after removing elements")

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.

append()- It appends ‘a’, ‘b’, and ‘c’ to the queue and

pop.left()-dequeues the element in the queue

Uncommenting q.popleft() after the queue is empty would raise an IndexError

Example:

from collections import deque

q = deque()

q.append('a')

q.append('b')

q.append('c')

print("Initial queue")

print(q)

print("\nElements dequeued from the queue")

print(q.popleft())

print(q.popleft())

print(q.popleft())

print("\nQueue after removing elements")


print(q)

Implementation using queue.Queue


Queue is built-in module of Python which is used to implement a queue.
queue.Queue(maxsize) initializes a variable to a maximum size of maxsize. A maxsize
of zero ‘0’ means a infinite queue. This Queue follows FIFO rule.
There are various functions available in this module:
 maxsize – Number of items allowed in the queue.
 empty() – Return True if the queue is empty, False otherwise.
 full() – Return True if there are maxsize items in the queue. If the queue was
initialized with maxsize=0 (the default), then full() never returns True.
 get() – Remove and return an item from the queue. If queue is empty, wait until an
item is available.
 get_nowait() – Return an item if one is immediately available, else raise
QueueEmpty.
 put(item) – Put an item into the queue. If the queue is full, wait until a free slot is
available before adding the item.
 put_nowait(item) – Put an item into the queue without blocking. If no free slot is
immediately available, raise QueueFull.
 qsize() – Return the number of items in the queue.

Example:

# implment queue using queue module


from queue import Queue
q=Queue(maxsize=4)
print("Initial Size Before Insertion:",q.qsize())
q.put('A')
q.put('AA')
q.put('AAA')
q.put('AAAA')
print("After Insertion:",q.qsize())
print("Queue is Full or Not:",q.full())
print("Size of Queue:",q.qsize())
print("Removing Elements:")
print(q.get())
print(q.get())
print(q.get())
print("Empty or Not??",q.empty())
print(q.get())
print("Empty or Not??",q.empty())
print("Size of Queue:",q.qsize())

Multithreading in Python

A threading module is provided by Python that enables the construction and

administration of threads in a Python programme. The threading module makes

Implementing multithreaded applications easier, which offers a high-level interface

for working with threads.

Different Ways to Create a Thread in Python

There are two ways in which we can create a thread in python. They are as follows:

1. Creating a Thread with pre-defined ‘Thread’ class

2. Creating a our own thread class by inheriting Thread class

Thread modules

It is started with Python 3, designated as obsolete, and can only be accessed with _thread
that supports backward compatibility.

Syntax:

1. thread.start_new_thread ( function_name, args[, kwargs] )


To implement the thread module in Python, we need to import a thread module and then
define a function that performs some action by setting the target with a variable.

Threading Modules

The threading module is a high-level implementation of multithreading used to deploy an


application in Python. To use multithreading, we need to import the threading module in
Python Program.

Thread Class Methods

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:

1. Import the threading module

Create a new thread by importing the threading module, as shown.

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.

1. Syntax: thread.start_new_thread ( function_name, args[, kwargs] )

o Target: It defines the function name that is executed by the thread.

o Args: It defines the arguments that are passed to the target function name.

For example:

1. import threading

2. def print_hello(n):

3. print("Hello, how old are you ", n)

4. t1 = threading.Thread( target = print_hello, args =(18, ))

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):

3. Print("Hello, how old are you? ", n)

4. T1 = threading.Thread( target = print_hello, args = (20, ))

5. T1.start()

6. T1.join()

7. Print("Thank you")

Output:

Hello, how old are you? 20

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

Program: Creating a Thread with pre-defined ‘Thread’ class in python (demo3.py)

from threading import *

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")

Creating a Thread class by inheriting Thread class:

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.

Program: Creating a Thread class by inheriting Thread class in python (demo4.py)

from threading import *

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")

Naming a Thread in Python:

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.

object.setName(<name>) : To set our own name


object.getName() – Returns Name of Thread

Program: set and get the name of a thread in python (demo7.py)

from threading import *

print("Main thread name",current_thread().getName())

current_thread().setName("MyThread")

print("After customise the thread name: ",current_thread().getName())

Output:

As already stated, current_thread() will return an object to the current thread. By the
default the program runs on Main Thread.

Thread Identification Number (ident):

For every thread internally, a unique identification number will be available. We can
access this by using implicit variable “ident”.

Program: Thread Identification Number in python (demo8.py)

from threading import *

def m():

print("Child Thread")

t=Thread(target=m)

t.start()

print("Main Thread Identification Number:", current_thread().ident)

print("Child Thread Identification Number:", t.ident)

Methods of Thread class in Python

the following important methods of Thread class in detail.


1. active_count()

2. enumerate()

3. isAlive()

4. join()

5. join(seconds)

active_count() method:

This function returns the number of active threads currently running.

Program: active_count() method of Thread class in Python

from threading import *

import time

def display():

print(current_thread().getName(), "...started")

time.sleep(3)

print(current_thread().getName(), "...ended")

print("The Number of active Threads:", active_count())

t1=Thread(target=display, name="ChildThread1")

t2=Thread(target=display, name="ChildThread2")

t3=Thread(target=display, name="ChildThread3")

t1.start()

t2.start()

t3.start()

print("The Number of active Threads:", active_count())


time.sleep(5)

print("The Number of active Threads:", active_count())

enumerate() function:

This function returns a list of the objects of all active threads currently running.

Program: enumerate() function of Thread class (demo10.py)

from threading import *

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:

print("Thread Name:", t.name)

time.sleep(5)
l=enumerate()

for t in l:

print("Thread Name:", t.name)

isAlive() method:

This method is used to check whether a thread is still executing or not.

Program: isAlive() method in Python (demo11.py)

from threading import *

import time

def display():

print(current_thread().getName(), "...started")

time.sleep(3)

print(current_thread().getName(), "...ended")

print("The Number of active Threads:", active_count())

t1=Thread(target=display, name="ChildThread1")

t2=Thread(target=display, name="ChildThread2")

t1.start()

t2.start()

print(t1.name,"is Alive :",t1.isAlive())

print(t2.name,"is Alive :",t2.isAlive())

time.sleep(5)

print(t1.name,"is Alive :",t1.isAlive())

print(t2.name,"is Alive :",t2.isAlive())


Output:

join() method:

If we want a particular thread to wait for another thread to complete, then we can use
join() method.

Program: join() method of Thread class (demo12.py)

from threading import *

import time

def display():

for i in range(5):

print("First Thread")

t=Thread(target=display, name="ChildThread")

t.start()

t.join() #This is executed by Main Thread

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)

from threading import *

import time

def display():

for i in range(5):

print("First Thread")

time.sleep(2)

t=Thread(target=display, name="ChildThread")

t.start()

t.join(5) #This is executed by Main Thread

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)

Example: Garbage Collector

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.

Program: Checking whether the Thread is Daemon or not in Python (demo14.py)

from threading import *

print(current_thread().isDaemon())

print(current_thread().daemon)

setDaemon() method in python:

We can change Daemon nature by using the setDaemon() method of Thread class. In this
perspective, let’s know some points.

Program: setDaemon() method of Thread class in Python (demo15.py)

from threading import *

def display():

print("Child Thread")

t=Thread(target=display)

t.start()

t.setDaemon(True)

Output:

from threading import *

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)

print("End Of Main Thread")

You might also like