3 Weird Python Scripts That Will Impress Your Colleagues
Tired of the same old Python tutorials? Discover 3 weird but impressive Python scripts to wow your colleagues, from a mouse jiggler to an ASCII video player.
Alex Grayson
A senior Python developer and tech writer who loves building wonderfully useless things.
Let's be honest. As developers, we spend most of our days wrangling data, building APIs, and fixing bugs that make us question our life choices. We use Python as a powerful tool for serious business. But what about the fun side? What about using its incredible flexibility to do something... unexpected? Something that makes your colleagues lean over your shoulder and ask, "Whoa, how did you do that?"
Python isn't just for data science and web development. It's a magical wand for automation, creativity, and a bit of harmless mischief. The scripts we're about to explore aren't going to revolutionize your company's tech stack. They won't optimize your database queries. What they will do is showcase your skills in a fun, memorable way, and maybe even teach you a new library or concept along the journey.
So, close that Jira ticket for a minute, grab your favorite beverage, and let's dive into three weird, wonderful, and genuinely impressive Python scripts that are guaranteed to be more interesting than your last sprint planning meeting.
1. The "Always Active" Mouse Jiggler
We've all been there. You're deep in thought, reading documentation, or pair-programming with someone at their desk, and suddenly your Slack or Microsoft Teams status flips to "Away." It’s a small thing, but it can be annoying. Enter the mouse jiggler: a classic script that keeps you perpetually "Active."
This script uses the pyautogui
library to programmatically control your mouse. It’s a simple, elegant solution to a very modern problem.
Installation
First, you'll need to install the library. Open your terminal and run:
pip install pyautogui
The Code
import pyautogui
import time
import random
print("Mouse Jiggler is running. Press Ctrl-C to quit.")
try:
while True:
# Move the mouse to a random new position on the screen
x = random.randint(0, 500)
y = random.randint(0, 500)
pyautogui.moveTo(x, y, duration=0.5)
# Wait for a random interval (e.g., 1 to 3 minutes)
sleep_time = random.randint(60, 180)
print(f"Sleeping for {sleep_time} seconds...")
time.sleep(sleep_time)
except KeyboardInterrupt:
print("\nMouse Jiggler stopped.")
How It Works
import pyautogui, time, random
: We import the necessary libraries.pyautogui
for mouse control,time
to pause the script, andrandom
to make the movements and pauses unpredictable.while True:
: This creates an infinite loop that keeps the script running until you manually stop it (with Ctrl-C).pyautogui.moveTo(x, y, duration=0.5)
: This is the core function. It moves the mouse cursor to the random coordinates(x, y)
over a period of 0.5 seconds, making the movement look more natural.time.sleep(random.randint(60, 180))
: The script then pauses for a random duration between 60 and 180 seconds. This prevents the mouse from moving too predictably.
A Quick Ethical Note: This is a fun tool for personal convenience. Be mindful of your workplace policies. The goal is to avoid appearing inactive while you're actively thinking or working away from your keyboard, not to deceive anyone about your work hours!
2. The Instant XKCD Comic Viewer
If you're in tech, you probably love XKCD. Randall Munroe's webcomic about "romance, sarcasm, math, and language" is a cultural touchstone. Why not build a script that fetches the latest comic for you? It's a fantastic, bite-sized introduction to web scraping.
This script uses requests
to download the web page and BeautifulSoup
to parse the HTML and find the comic image.
Installation
You'll need two libraries for this one:
pip install requests beautifulsoup4
The Code
import requests
from bs4 import BeautifulSoup
import webbrowser
import random
def get_latest_xkcd():
"""Fetches the URL of the latest XKCD comic."""
try:
response = requests.get("https://xkcd.com/")
response.raise_for_status() # Raise an exception for bad status codes
soup = BeautifulSoup(response.text, 'html.parser')
comic_element = soup.select_one("#comic img")
if comic_element and comic_element['src']:
return f"https:{comic_element['src']}"
except requests.exceptions.RequestException as e:
print(f"Error fetching XKCD page: {e}")
return None
def open_comic_in_browser(url):
"""Opens a given URL in the default web browser."""
if url:
print(f"Opening comic: {url}")
webbrowser.open(url)
else:
print("Could not find the comic URL.")
if __name__ == "__main__":
print("Fetching the latest XKCD comic...")
latest_comic_url = get_latest_xkcd()
open_comic_in_browser(latest_comic_url)
How It Works
requests.get("https://xkcd.com/")
: This line sends an HTTP GET request to the XKCD homepage and downloads its HTML content.BeautifulSoup(response.text, 'html.parser')
: We create a `BeautifulSoup` object, which turns the raw HTML text into a structured, searchable object.soup.select_one("#comic img")
: This is the web scraping magic. We use a CSS selector to find the `` tag that is inside the `
` with the ID `comic`. This is where the comic image is consistently located on the site.webbrowser.open(url)
: Finally, this standard library function opens the image URL in your default web browser for instant viewing.Run this script, and in seconds, you'll have the latest comic open and ready to read. Your colleagues will be impressed by how you've automated your procrastination!
3. The Real-Time ASCII Art Video Player
This is the showstopper. The grand finale. We're going to use Python to capture your webcam feed and render it as live ASCII art directly in your terminal. It’s visually stunning, delightfully nerdy, and a brilliant demonstration of real-time video processing.
We'll be using
opencv-python
, a powerful library for computer vision tasks.Installation
OpenCV is a heavy-duty library, but installation is straightforward with pip:
pip install opencv-python numpy
The Code
import cv2 import os import numpy as np # A string of characters from dark to light ASCII_CHARS = "@%#*+=-:. " def resize_frame(frame, new_width=100): """Resize a frame to a new width while maintaining aspect ratio.""" (old_height, old_width) = frame.shape aspect_ratio = old_height / float(old_width) new_height = int(aspect_ratio * new_width * 0.55) # 0.55 is a correction factor for char aspect ratio return cv2.resize(frame, (new_width, new_height)) def frame_to_ascii(frame): """Convert a grayscale frame to an ASCII string.""" frame = (frame / 255.0 * (len(ASCII_CHARS) - 1)).astype(np.uint8) ascii_str = "" for row in frame: for pixel_value in row: ascii_str += ASCII_CHARS[pixel_value] ascii_str += "\n" return ascii_str def main(): cap = cv2.VideoCapture(0) # 0 is the default webcam if not cap.isOpened(): print("Error: Could not open video stream.") return try: while True: ret, frame = cap.read() if not ret: break gray_frame = cv2.cvtColor(frame, cv.COLOR_BGR2GRAY) resized_frame = resize_frame(gray_frame, new_width=120) ascii_art = frame_to_ascii(resized_frame) os.system('cls' if os.name == 'nt' else 'clear') print(ascii_art) # A way to exit the loop. OpenCV waitKey is a good option. # This part is tricky in a pure terminal script, so we'll let Ctrl-C handle it. time.sleep(0.03) # Frame rate control except KeyboardInterrupt: print("Stream stopped.") finally: cap.release() if __name__ == "__main__": main()
How It Works
cv2.VideoCapture(0)
: This initializes a video capture object for your primary webcam.- The Main Loop: The script continuously reads frames from the webcam.
cv2.cvtColor(...)
: Each frame (which is a color image) is converted to grayscale, as brightness is all we need for ASCII conversion.resize_frame(...)
: This is crucial. A full HD frame has millions of pixels. We resize it to a width that fits the terminal (e.g., 120 characters) to make processing fast and the output viewable.frame_to_ascii(...)
: This is the core logic. It maps the brightness of each pixel (0-255) to a character in our `ASCII_CHARS` string. Dark pixels get a dense character like '@', while light pixels get a sparse one like '.'.os.system('cls' or 'clear')
: This command clears the terminal screen before printing the next frame, creating the illusion of a smooth animation.
Run this script, and your terminal will spring to life with a retro, cyberpunk version of your face. Your colleagues won't know what hit them.
4. Why Bother With Weird Scripts?
While a mouse jiggler or an ASCII video converter might not be part of your next production release, they serve a vital purpose. They keep programming fun. They encourage creative problem-solving and provide a low-stakes environment to experiment with powerful libraries like
pyautogui
,BeautifulSoup
, andOpenCV
.These "weird" projects are the perfect answer to the question, "What should I build to practice my Python skills?" They are tangible, rewarding, and, most importantly, impressive. So go ahead, give them a try, and see what other wonderfully weird ideas you can bring to life with a few lines of Python.
What's the weirdest script you've ever written? Share it in the comments below!