0% found this document useful (0 votes)
0 views

CT-2 Python practical programs (2)

The document contains multiple Python programs demonstrating various functionalities such as interacting with the operating system using the os module, file operations with the shutil module, directory tree traversal, parallel computing, command line argument handling, socket programming for network communication, dynamic user interaction with a GUI, XML data processing using SAX and DOM parsers. Each program is self-contained and showcases specific programming concepts and techniques. The document serves as a comprehensive guide for practical Python programming applications.

Uploaded by

dummy10802
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

CT-2 Python practical programs (2)

The document contains multiple Python programs demonstrating various functionalities such as interacting with the operating system using the os module, file operations with the shutil module, directory tree traversal, parallel computing, command line argument handling, socket programming for network communication, dynamic user interaction with a GUI, XML data processing using SAX and DOM parsers. Each program is self-contained and showcases specific programming concepts and techniques. The document serves as a comprehensive guide for practical Python programming applications.

Uploaded by

dummy10802
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

1.

Write a program to intersect with the operating


system using os module: 1)Display current working
directory 2)List all files and directory 3)Create a new
directory 4)Remove an empty directory 5)Run a shell
command. in python
import os

def display_current_directory():

current_directory = os.getcwd() # Get the current working directory

print(f"Current Working Directory: {current_directory}")

def list_files_and_directories():

files_and_dirs = os.listdir() # List files and directories in the current working directory

print("Files and Directories in the Current Directory:")

for item in files_and_dirs:

print(item)

def create_new_directory(directory_name):

try:

os.mkdir(directory_name) # Create a new directory

print(f"Directory '{directory_name}' created successfully.")

except FileExistsError:

print(f"Directory '{directory_name}' already exists.")

except Exception as e:

print(f"An error occurred: {e}")

def remove_empty_directory(directory_name):

try:

os.rmdir(directory_name) # Remove an empty directory

print(f"Directory '{directory_name}' removed successfully.")

except FileNotFoundError:

print(f"Directory '{directory_name}' does not exist.")


except OSError:

print(f"Directory '{directory_name}' is not empty or cannot be removed.")

except Exception as e:

print(f"An error occurred: {e}")

def run_shell_command(command):

try:

os.system(command) # Run a shell command

print(f"Shell command '{command}' executed.")

except Exception as e:

print(f"An error occurred while running the shell command: {e}")

if __name__ == "__main__":

display_current_directory()

list_files_and_directories()

create_new_directory('test_directory')

remove_empty_directory('test_directory')

run_shell_command('echo Hello World')

2. Write a program for file operations using ‘shutil’


module and collect information about os architecture
and processor: 1)Copy a file 2)Move a file 3)Remove a
directory 4)OS name 5)OS version 6)Processor details in
python

import shutil

import os

import platform

import psutil

def copy_file(src, dst):

try:
shutil.copy(src, dst) # Copy file from src to dst

print(f"File copied from {src} to {dst}")

except FileNotFoundError:

print(f"Source file {src} not found.")

except Exception as e:

print(f"Error while copying file: {e}")

def move_file(src, dst):

try:

shutil.move(src, dst) # Move file from src to dst

print(f"File moved from {src} to {dst}")

except FileNotFoundError:

print(f"Source file {src} not found.")

except Exception as e:

print(f"Error while moving file: {e}")

def remove_directory(directory_name):

try:

shutil.rmtree(directory_name) # Remove a directory and all its contents

print(f"Directory {directory_name} and its contents removed successfully.")

except FileNotFoundError:

print(f"Directory {directory_name} does not exist.")

except Exception as e:

print(f"Error while removing directory: {e}")

def get_os_name():

os_name = platform.system() # Get the name of the operating system

print(f"Operating System: {os_name}")

def get_os_version():

os_version = platform.version() # Get the version of the OS


print(f"OS Version: {os_version}")

def get_processor_details():

processor = platform.processor() # Get the processor name

print(f"Processor: {processor}")

cpu_count = psutil.cpu_count(logical=True) # Logical cores

cpu_physical = psutil.cpu_count(logical=False) # Physical cores

print(f"Logical CPUs: {cpu_count}")

print(f"Physical CPUs: {cpu_physical}")

if __name__ == "__main__":

copy_file('source_file.txt', 'destination_file.txt')

move_file('destination_file.txt', 'moved_file.txt')

remove_directory('test_directory')

get_os_name()

get_os_version()

get_processor_details()

3. Write a program for directory tree traversal using


os.walk() method. in python
import os

def traverse_directory_tree(root_dir):

for dirpath, dirnames, filenames in os.walk(root_dir):


print(f"Current Directory: {dirpath}")

if dirnames:

print("Subdirectories:")

for dirname in dirnames:

print(f" - {dirname}")

else:

print("No subdirectories.")

if filenames:

print("Files:")

for filename in filenames:

print(f" - {filename}")

else:

print("No files.")

print("="*40)

root_directory = "."

traverse_directory_tree(root_directory)

4. Write a program in python for parallel computing by


using any one parallel system tool. in python without
comment lines

import concurrent.futures

import time

def compute_square(n):

time.sleep(1)
return n * n

def compute_cube(n):

time.sleep(1)

return n * n * n

def main():

numbers = [1, 2, 3, 4, 5]

with concurrent.futures.ThreadPoolExecutor() as executor:

square_results = executor.map(compute_square, numbers)

cube_results = executor.map(compute_cube, numbers)

print("Squares:", list(square_results))

print("Cubes:", list(cube_results))

if __name__ == "__main__":

main()

5. Write a program to terminate the execution of a


python program or exit the python interpreter: 1)quit()
2) exit() 3)sys.exit() 4)os._exit() in python without
coments line

import sys

import os

def terminate_program(method):

if method == 1:

print("Using quit() to terminate the program.")

quit()

elif method == 2:
print("Using exit() to terminate the program.")

exit()

elif method == 3:

print("Using sys.exit() to terminate the program.")

sys.exit()

elif method == 4:

print("Using os._exit() to terminate the program.")

os._exit(0)

terminate_program(3)

6. Write a program for handling command line


arguments using below mentioned module: 1)sys.argv
2)getopt module 3)argparse module

import sys

import getopt

import argparse

def sys_argv_example():

print("Using sys.argv:")

for arg in sys.argv:

print(arg)

def getopt_example():

print("Using getopt:")

args = sys.argv[1:] # Skip the script name

opts, _ = getopt.getopt(args, "a:b:")

for opt, value in opts:

print(f"{opt} {value}")
def argparse_example():

print("Using argparse:")

parser = argparse.ArgumentParser()

parser.add_argument("-a", type=int, help="First argument")

parser.add_argument("-b", type=int, help="Second argument")

args = parser.parse_args() # Parse the arguments

print(f"a = {args.a}, b = {args.b}")

if __name__ == "__main__":

# Manually set sys.argv to simulate command-line arguments

sys.argv = ['command_line_args.py', '-a', '10', '-b', '20']

sys_argv_example()

getopt_example()

argparse_example()

UNIT-4

7. Write a program to communicate between two


nodes connected in network.(socket
programming)
import socket

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server_socket.bind(('0.0.0.0', 12345))

server_socket.listen(5)

print("Server listening on 0.0.0.0:12345...")

while True:

client_socket, addr = server_socket.accept()

print(f"Connected to {addr}")

data = client_socket.recv(1024).decode()
print(f"Client says: {data}")

client_socket.send("Message received successfully!".encode())

client_socket.close()

Save the above code as “Server.py”

import socket

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

client_socket.connect(('127.0.0.1', 12345))

client_socket.send("Hello, Server!".encode())

response = client_socket.recv(1024).decode()

print(f"Server response: {response}")

client_socket.close()

Save the above code as “ Client.py”

8. Write a program to establish a dynamic


interaction between a web application and the
browser.(cell script with user interaction)

import tkinter as tk

from tkinter import ttk

def button_click():

output_label.config(text="Button clicked!")

def submit_click():

user_input = input_entry.get()

if user_input:

output_label.config(text=f"You entered: {user_input}")

input_entry.delete(0, tk.END) # Clear the input field


else:

output_label.config(text="Please enter something!")

def enter_pressed(event):

submit_click()

root = tk.Tk()

root.title("Dynamic Interaction")

output_label = ttk.Label(root, text="Waiting for user interaction...")

output_label.pack(pady=10)

button = ttk.Button(root, text="Click Me!", command=button_click)

button.pack(pady=5)

input_entry = ttk.Entry(root)

input_entry.pack(pady=5)

input_entry.bind("<Return>", enter_pressed) #Bind enter key to submit

submit_button = ttk.Button(root, text="Submit", command=submit_click)

submit_button.pack(pady=5)

root.mainloop()

9. Write a program in python to process xml data


using SAX parser(simple API for XML).

import xml.sax

class MyHandler(xml.sax.ContentHandler):

def __init__(self):
self.current_data = ""

self.title = ""

self.author = ""

self.year = ""

self.price = ""

def startElement(self, tag, attributes):

self.current_data = tag

def endElement(self, tag):

if self.current_data == "title":

print("Title:", self.title)

elif self.current_data == "author":

print("Author:", self.author)

elif self.current_data == "year":

print("Year:", self.year)

elif self.current_data == "price":

print("Price:", self.price)

self.current_data = ""

def characters(self, content):

if self.current_data == "title":

self.title = content

elif self.current_data == "author":

self.author = content

elif self.current_data == "year":

self.year = content

elif self.current_data == "price":

self.price = content

if __name__ == "__main__":
xml_data = """

<bookstore>

<book>

<title>Everyday Italian</title>

<author>Giada De Laurentiis</author>

<year>2005</year>

<price>30.00</price>

</book>

<book>

<title>Harry Potter</title>

<author>J K. Rowling</author>

<year>2005</year>

<price>29.99</price>

</book>

</bookstore>

"""

parser = xml.sax.make_parser()

parser.setFeature(xml.sax.handler.feature_namespaces, 0)

handler = MyHandler()

parser.setContentHandler(handler)

xml.sax.parseString(xml_data, handler)

10. Write a python program to process XML data


using Dom parser(Document object Model API).

from xml.dom.minidom import parse

# Parse the XML file

xml_file = "sample.xml" # Make sure this file exists

dom_tree = parse(xml_file)
# Get the root element

root = dom_tree.documentElement

print(f"Root Element: {root.tagName}")

# Get all "employee" elements

employees = root.getElementsByTagName("employee")

# Loop through employees and print details

for emp in employees:

emp_id = emp.getAttribute("id") # Get attribute

name = emp.getElementsByTagName("name")[0].childNodes[0].nodeValue

age = emp.getElementsByTagName("age")[0].childNodes[0].nodeValue

department = emp.getElementsByTagName("department")[0].childNodes[0].nodeValue

print(f"\nEmployee ID: {emp_id}")

print(f"Name: {name}")

print(f"Age: {age}")

print(f"Department: {department}")

Save the above code as “parser_xml.py”

<?xml version="1.0"?>

<company>

<employee id="101">

<name>Alice</name>

<age>30</age>

<department>HR</department>

</employee>

<employee id="102">

<name>Bob</name>

<age>35</age>
<department>IT</department>

</employee>

</company>

Save the above code as “sample.xml”

Now run the “ parser_xml.py “ code

You might also like