Top 10 Best Python Projects



 1. System Resource usage

  •  Libraries Used: psutil
This code retrieves various system resource usage information on a computer running Python, using the psutil library. The code defines a single function get_system_info, which retrieves the following information:

  1. import psutil

  2. def get_system_info():
  3. # Get CPU utilization
  4. cpu_percent = psutil.cpu_percent()
  5. print(f"CPU utilization: {cpu_percent}%")

  6. # Get battery information
  7. battery = psutil.sensors_battery()
  8. print(f"Battery charge: {battery.percent}%")

  9. # Get RAM utilization
  10. virtual_memory = psutil.virtual_memory()
  11. print(f"RAM utilization: {virtual_memory.percent}%")

  12. # Get available memory
  13. available_memory = virtual_memory.available / virtual_memory.total * 100
  14. print(f"Available memory: {available_memory:.2f}%")

  15. get_system_info()

Explanation : 
  • CPU utilization: The function uses psutil.cpu_percent() to get the current CPU utilization as a float value, which is then formatted as a string and printed to the console using an f-string.
  • Battery information: The function uses psutil.sensors_battery() to get information about the battery, and then prints the battery charge percentage, which is represented by the percent attribute of the returned object.
  • RAM utilization: The function uses psutil.virtual_memory() to get information about the system's virtual memory, and then prints the RAM utilization percentage, which is represented by the percent attribute of the returned object.
  • Available memory: The function calculates the available memory by dividing the available attribute of the psutil.virtual_memory() object by the total attribute, and multiplying by 100 to get the result in percentage. This value is then formatted as a string with two decimal places and printed to the console.
  • Finally, the get_system_info function is called at the end of the code, which executes the code and displays the results on the console.
You can add several other pieces of information about the system resources that psutil provides:
  • Disk usage: You can use psutil.disk_usage('/') to get information about disk usage, including total, used, and free space. You can then print this information to the console.
  • Network information: You can use psutil.net_io_counters() to get information about the network I/O (input/output) activity, such as bytes sent and received.
  • Boot time: You can use psutil.boot_time() to get the time when the system was last booted, which you can then format as a string and print to the console.
  • Logical disk partitions: You can use psutil.disk_partitions() to get information about the logical disk partitions on the system, including the device, mount point, file system type, and other information.
  • Process information: You can use psutil.process_iter() to iterate over all running processes and get information about each process, such as its name, status, memory usage, and CPU utilization.
  • # Get disk usage information
  • disk_usage = psutil.disk_usage('/')
  • print(f"Disk total: {disk_usage.total / (1024 ** 3):.2f} GB")
  • print(f"Disk used: {disk_usage.used / (1024 ** 3):.2f} GB")
  • print(f"Disk free: {disk_usage.free / (1024 ** 3):.2f} GB")

  • # Get network information
  • net_io_counters = psutil.net_io_counters()
  • print(f"Bytes sent: {net_io_counters.bytes_sent / (1024 ** 2)} MB")
  • print(f"Bytes received: {net_io_counters.bytes_recv / (1024 ** 2)} MB")

  • # Get boot time
  • boot_time = psutil.boot_time()
  • boot_time_str = datetime.datetime.fromtimestamp(boot_time).strftime('%Y-%m-%d %H:%M:%S')
  • print(f"System boot time: {boot_time_str}")

  •  Libraries Used: requests,bs4
Here's a simple Python code that uses the requests library and BeautifulSoup library to extract all the links from a website:
  1. import requests
  2. from bs4 import BeautifulSoup

  3. # Make a request to the website
  4. url = "https://www.learnpython.org/"
  5. page = requests.get(url)

  6. # Parse the HTML content of the page
  7. soup = BeautifulSoup(page.content, "html.parser")

  8. # Find all the anchor tags
  9. links = soup.find_all("a")

  10. # Extract the href attribute from each anchor tag
  11. for link in links:
  12. href = link.get("href")
  13. print(href)
This code makes a request to the website https://www.example.com, extracts the HTML content of the page, and uses the BeautifulSoup library to parse the HTML. The soup.find_all method is used to find all "a" elements (anchor tags), and the get method is used to extract the "href" attribute from each tag. The extracted links are printed to the console.

You can modify the code to extract links from any website you want by changing the URL in the requests.get method.

 3. Show Saved WiFi Password

This is a script written in Python that retrieves the saved Wi-Fi profiles and their passwords on a Windows machine using the subprocess module. The netsh command is used to retrieve the profiles and the profile information.

  •  Libraries Used: subprocess
  1. import subprocess

  2. data = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles']).decode('utf-8', errors="backslashreplace").split('\n')
  3. profiles = [i.split(":")[1][1:-1] for i in data if "All User Profile" in i]
  4. for i in profiles:
  5. try:
  6. results = subprocess.check_output(['netsh', 'wlan', 'show', 'profile', i, 'key=clear']).decode('utf-8', errors="backslashreplace").split('\n')
  7. results = [b.split(":")[1][1:-1] for b in results if "Key Content" in b]
  8. try:
  9. print ("{:<30}| {:<}".format(i, results[0]))
  10. except IndexError:
  11. print ("{:<30}| {:<}".format(i, ""))
  12. except subprocess.CalledProcessError:
  13. print ("{:<30}| {:<}".format(i, "ENCODING ERROR"))
  14. input("")
The check_output function is used to run the netsh command and retrieve the output. The output is then decoded from a byte string to a regular string using the decode method and split into lines using the split method with the newline character ('\n') as a separator. The resulting list of lines is then processed to extract the profile names and their passwords.

For each profile, the script tries to retrieve the password and if it succeeds, it prints the profile name and the password. If the password can't be retrieved, it prints "ENCODING ERROR". If the password exists, it will be displayed in clear text, which could be a security concern.

 4. Shortcut key with python

This code uses the pyautogui library to automate various actions on a Windows computer. The code performs the following actions:
  •  Libraries Used: pyautogui ,time
  1. import pyautogui
  2. from time import sleep

  3. # 1. Change tab : Wait for 5sec and switch
  4. pyautogui.keyDown("alt")
  5. pyautogui.press("tab")
  6. sleep(5)
  7. pyautogui.keyUp("alt")

  8. # 1.1 Direct change Tab
  9. # pyautogui.hotkey('alt','tab')

  10. # 2.Close current app
  11. pyautogui.hotkey('alt', 'f4')

  12. # 3.Open setting
  13. pyautogui.hotkey('winleft','i')

  14. # 4.Open the hidden menu
  15. pyautogui.hotkey('winleft','x')

  16. # 5.Open the Task Manager
  17. pyautogui.hotkey('ctrl','shift','esc')

  18. # 6.Open the Task view
  19. pyautogui.hotkey('winleft','tab')

  20. # 7.TAKE Screenshot
  21. pyautogui.hotkey('winleft','prtscr')

  22. # 8.TAKE SNIP
  23. pyautogui.hotkey('winleft','shift','s')

  24. # 9.Add a new virtual desktop
  25. pyautogui.hotkey('winleft','ctrl','d')

  26. # 10. open system properties
  27. pyautogui.hotkey('winleft','r')
  28. pyautogui.typewrite("sysdm.cpl\n", interval=0.1)
Here is an example code that automates the process of opening Notepad, typing some text, and saving the file:

 5. Notepad Automation

  •  Libraries Used: pyautogui, time
  1. import pyautogui
  2. from time import sleep

  3. # Open Notepad
  4. pyautogui.hotkey('winleft')
  5. pyautogui.typewrite('notepad\n', interval=0.5)

  6. # Wait for Notepad to open
  7. sleep(2)

  8. # Type some text in Notepad
  9. pyautogui.typewrite("Hello, this is automated text from codesempai", interval=0.1)

  10. # Save the file
  11. pyautogui.hotkey('ctrl', 's')

  12. # Wait for the Save As dialog to appear
  13. sleep(2)

  14. # Type the file name and press Enter
  15. pyautogui.typewrite("sample.txt\n", interval=0.1)

  16. # Close Notepad
  17. pyautogui.hotkey('alt', 'f4')
This code uses the pyautogui library to automate the process of opening Notepad, typing some text, and saving the file. It uses the hotkey function to open the Start menu, search for Notepad, and save the file, and the typewrite function to type text in Notepad and the file name. The sleep function is used to wait for Notepad to open and the Save As dialog to appear.

 6. Youtube Automation

This code uses the pyautogui library to automate actions on a Windows computer. The code consists of two parts: a function open_chrome_and_visit_youtube and a block of code that calls the function.
  •  Libraries Used: pyautogui 
  1. import pyautogui as pg

  2. def open_chrome_and_visit_youtube():
  3. # Open the start menu
  4. pg.hotkey('winleft')

  5. # Type "chrome" and press Enter
  6. pg.typewrite('chrome\n', interval=0.5)

  7. # Type "www.youtube.com" and press Enter
  8. pg.typewrite('www.youtube.com\n', interval=0.2)

  9. # Move the focus to the Chrome window and maximize it
  10. pg.hotkey('winleft', 'up')

  11. # Open a new tab in Chrome
  12. pg.hotkey('ctrl', 't')


  13. if __name__ == "__main__":
  14. open_chrome_and_visit_youtube()
The open_chrome_and_visit_youtube function performs the following actions:

  • It opens the Windows start menu using the pg.hotkey('winleft') function.
  • It types the word "chrome" in the search bar and presses Enter using the pg.typewrite('chrome\n', interval=0.5) function. The interval argument specifies the time in seconds between keypresses.
  • It types the URL "www.youtube.com" in the address bar of the Chrome browser and presses Enter using the pg.typewrite('www.youtube.com\n', interval=0.2) function.
  • It moves the focus to the Chrome window and maximizes it using the pg.hotkey('winleft', 'up') function.
  • It opens a new tab in the Chrome browser using the pg.hotkey('ctrl', 't') function.
The second part of the code, the if __name__ == "__main__": block, ensures that the open_chrome_and_visit_youtube function is only executed when the script is run directly (i.e., not imported as a module). When executed, the function opens Chrome, navigates to the YouTube website, maximizes the window, and opens a new tab.

 7. Change wallpapers!

This is a Python script that sets a random wallpaper from a directory as the desktop background on a Windows computer. The ctypes module is used to interact with the Windows API and set the wallpaper using the SystemParametersInfoW function.
  •  Libraries Used: ctypes,os,random
  1. import ctypes
  2. import os
  3. import random

  4. def set_random_wallpaper(dir):

  5. afolder = os.listdir(dir)
  6. folder = dir + "/" + random.choice(afolder)
  7. print(folder)
  8. ctypes.windll.user32.SystemParametersInfoW(20, 0, folder, 3)

  9. set_random_wallpaper("D:/Wallpapers/best of")

The set_random_wallpaper function takes a directory as an argument, which is assumed to contain subdirectories of wallpapers. The function first lists the contents of the directory and selects a random subdirectory. The path of the selected subdirectory is then passed as an argument to SystemParametersInfoW along with the appropriate parameters to set it as the desktop background.


Note that the script assumes that the subdirectories in the specified directory contain wallpapers and that the wallpapers are in a format supported by Windows (e.g. JPEG, BMP, etc.). Additionally, the script assumes that the path to the directory is correctly specified and that the user running the script has the necessary permissions to change the desktop background.

 8. Test Internet Speed

This is a Python script that uses the "speedtest" library to measure the download speed of the internet connection. 
  •  Libraries Used: speedtest
  1. import speedtest

  2. speed_test = speedtest.Speedtest()

  3. def bytes_to_mb(bytes):
  4. KB = 1024 # One Kilobyte is 1024 bytes
  5. MB = KB * 1024 # One MB is 1024 KB
  6. return int(bytes/MB)

  7. print("please wait for few seconds...")
  8. download_speed = bytes_to_mb(speed_test.download())
  9. print("Your Download speed is", download_speed, "MB")

It defines a function called "bytes_to_mb" to convert the download speed from bytes to megabytes. It then prints a message to the user to wait for a few seconds, measures the download speed using the speed_test object, converts the result to megabytes using the bytes_to_mb function, and prints the download speed to the user in megabytes.

 9. Get Computer specs

This code uses the 'wmi' library to collect system information, including the operating system name and version, CPU model, amount of RAM, and graphics card model. 
The collected information is then printed on the console.
  •  Libraries Used: wmi
    1. import wmi

    2. try:
    3. computer = wmi.WMI()
    4. computer_info = computer.Win32_ComputerSystem()[0]
    5. os_info = computer.Win32_OperatingSystem()[0]
    6. proc_info = computer.Win32_Processor()[0]
    7. gpu_info = computer.Win32_VideoController()[0]

    8. os_name = os_info.Name.encode('utf-8').split(b'|')[0].decode()
    9. os_version = f"{os_info.Version} {os_info.BuildNumber}"
    10. system_ram = float(os_info.TotalVisibleMemorySize) / 1048576 # KB to GB

    11. print(f"OS Name: {os_name}")
    12. print(f"OS Version: {os_version}")
    13. print(f"CPU: {proc_info.Name}")
    14. print(f"RAM: {system_ram:.2f} GB")
    15. print(f"Graphics Card: {gpu_info.Name}")

    16. except Exception as e:
    17. print(f"Error: {e}")
    In this updated code, we use a try and except block to catch any exceptions that might occur during the system information retrieval. We also use f-strings for formatting the output, which makes the code more readable. Finally, we decode the os_name string from bytes to a regular string, and we format the RAM output to two decimal places.

     10. Countdown Timer 

    This code defines a functioning countdown that takes a single argument t, representing the number of seconds to count down.
    •  Libraries Used: Time, sys
    # Using While Loop : 
    1. import time
    2. import sys

    3. def countdown(t): #defineing the function name countdown
    4. while t > 0:
    5. sys.stdout.write('\rDuration : {}s'.format(t))
    6. t -= 1
    7. sys.stdout.flush()
    8. time.sleep(1)


    9. countdown(10) #calling the function
    Explanation: The function uses a while loop to count down from the value of t to zero. 
    •  The sys.stdout.write method is used to display the current time in seconds remaining, 
    • while sys.stdout.flush is used to ensure that the output is displayed immediately instead of being buffered. 
    • Finally, the time.sleep function is used to pause the program for one second between each iteration of the loop.
    When the function is called with a countdown(10), it will display a countdown from 10 to 1, with a one-second delay between each iteration, before the program terminates.

    # Using For Loop : 
    1. import time
    2. import sys

    3. def countdown(t: int) -> None:
    4. for i in range(t, 0, -1):
    5. sys.stdout.write('\rDuration : {}s'.format(i))
    6. sys.stdout.flush()
    7. time.sleep(1)
    8. print()

    9. countdown(10)

    Explanation: This code implements a countdown timer in Python. The countdown function takes a single argument t, which represents the duration of the timer in seconds.

    The function uses a for loop that starts from t and goes down to 0, decrementing by 1 on each iteration. 
    • The sys.stdout.write method is used to write the current countdown value to the standard output, which is typically the terminal. 
    • The sys.stdout.flush method is used to force the standard output to be immediately updated, so the countdown value appears correctly on the same line, rather than being printed on multiple lines.
    • The time.sleep(1) call is used to pause the execution of the program for 1 second so that the countdown timer progresses at a rate of 1 second per iteration.

    Finally, after the loop has completed, the print() statement is used to add a new line character to the standard output, so that the next line of output appears on a new line

    Post a Comment

    Previous Post Next Post