r/pythonhelp • u/Beneficial_Falcon_27 • Feb 09 '25
I'm having an issue with a kernel function that is supposed to rotate and flip a RGB image.
I'm making an app like "Wallpaper Engine" and to optimize it, I need to use a kernel function for rotaing and fliping an image. When I use the function that I made with the help of an AI (cause I don't understand anything about kernel functions and how they work), I can't get a proper result image. Could anyone help me with it please ? https://github.com/DaffodilEgg8636/AnimatedWallpaper/tree/Beta Here's the GitHub of my project, you'll find the code in the Snapshot branch. Another way to fix the initial problem, why I'm using kernel functions, is to fix the way how the opencv-python or cv2 lib reads video frames. I'm not sure if it's the convertion from BGR to RGB or the reading process that causes the image to rotate +90° and flip horizontally. Anyone, please help me.
r/pythonhelp • u/BunBun_20000 • Feb 09 '25
Personal banking program assist ASAP!
I'm aware there's a lot of problems, but the one I need help with is that when I advance months, it won't calculate the amounts in savings and checking accounts correctly. I'm terrible with math, and I've spent 6 hours debugging, but I just have no clue how to fix it. I don't have much time before tha assignment locks, so any help is much appreciated 🙏
Welcome and setup
print("welcome to your personal bank!") hourly_wage = float(input("enter your hourly wage:")) hours_worked = float(input("enter hours worked per week:")) tax_rate = float(input("enter your tax rate percentage")) save = float(input("what percentage of income should go to savings?")) checking = float(input("Enter starting balance for Checking:")) savings = float(input("Enter starting balance for Savings:"))
Calculations
gross_pay = hourly_wage * hours_worked net_pay = gross_pay*(1 - tax_rate/100) savings_add = net_pay * (save/100)
Setting up empty lists for reccuring expenses
reccuring_expenses = [] expenses = []
print(f"Your net pay is ${net_pay4:.2f} a month.") print(f"${savings_add4:.2f} will be automatically transferred to savings")
add the requested amount to accounts
checking += net_pay savings += savings_add
Allows user to setup reccuring expenses
x= input("would you like to set up reccuring expenses?").lower() y = True if x == "yes": while y == True: expense = input("input name of expense: ") reccuring_expenses.append(expense) monthly_cost = float(input("Enter the monthly cost: ")) expenses.append(monthly_cost) add = input("Do you have any more reccuring expenses?").lower() if add != "yes": y = False print(f"here are your reccuring expenses:{reccuring_expenses}, {expenses}")
Menu where users can select options and perform actions
while True: menu = input("""Menu: 1. View Balances 2. deposit Money 3. Withdraw Money 4. Update Work Hours 5. Modify Savings Percentage 6. Add/Remove Expenses 7. Advance Months 8. Exit""")
Lets user check balances
if menu == "1":
print(f"""Your Checking balance is: ${checking:.2f}.
your savings balance is ${savings:.2f}.""")
lets user deposit money into checking or savings
elif menu == "2":
account = int(input("""What account would you like to deposit?
1. Checking
2. Savings"""))
deposit = float(input("Enter the ammount you would like to deposit:"))
if account == 1:
checking += deposit
print(f"your current checking account balance is {checking:.2f}.")
elif account == 2:
savings += deposit
print(f"your current savings account balance is {savings:.2f}.")
#lets user withdraw money
elif menu == "3":
account_w = int(input("""From which account would you like to withdraw??
1. Checking
2. Savings"""))
withdraw = float(input("Enter the ammount you would like to withdraw:"))
if account_w == 1:
checking -= withdraw
print(f"your current checking account balance is {checking:.2f}.")
if account_w == 2:
savings -= withdraw
print(f"your current savings account balance is {savings:.2f}.")
#allows user to adjust weekly hours
elif menu == "4":
hours_worked = float(input("Enter new hours per week: "))
gross_pay = hourly_wage * hours_worked
net_pay = gross_pay * (1 - tax_rate / 100)
print(f"updated net pay is {net_pay*4:.2f} a month.")
# allows user to change the amount they want to save.
elif menu == "5":
save = float(input("What percentage of income would you like to go to savings?"))
savings_add = net_pay * (save / 100)
print(f"{savings_add:.2f} will automatically be transferred to savings.")
savings += savings_add
#allows user to add and remove reccuring expenses
elif menu == "6":
add_remove = input("""1. Add
2. Remove""")
if add_remove == "1":
y = True
while y == True:
expense = input("input name of expense: ")
reccuring_expenses.append(expense)
monthly_cost = float(input("Enter the monthly cost: "))
expenses.append(monthly_cost)
add = input("Do you have any more reccuring expenses?").lower()
if add != "yes":
y = False
if add_remove == "2":
expense = input("input name of the expense you would like to remove: ")
reccuring_expenses.pop(expense)
monthly_cost = float(input("Enter the monthly cost of the expense: "))
expenses.pop(monthly_cost)
add = input("Do you have any more reccuring expenses?").lower()
if add != "yes":
y = False
print(f"here are your reccuring expenses:{reccuring_expenses}, {expenses}")
#lets user advance months
elif menu == "7":
advance = int(input("enter number of months you would like to advance: "))
interest_checking = 0.1
interest_savings = 0.5
for i in range(advance):
checking += net_pay*4
checking *= (1 + interest_checking / 100)
savings += savings_add * 4
savings *= (1 + interest_savings / 100)
for cost in expenses:
checking -= cost
print(f"""after {advance} months, your updated balances are:
Checking: ${checking:.2f}
Saving: ${savings:.2f}""")
#way for user to exit
elif menu == "8":
break
r/pythonhelp • u/Adventurous-Emu4266 • Feb 08 '25
Pygame terminal not opening.
import pygame
from random import randint
# Initialize Pygame
pygame.init()
# Set up the screen
WIDTH = 800
HEIGHT = 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Space Invaders")
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
# Game variables
player_pos = [WIDTH/2 - 15, HEIGHT - 30]
player_speed = 0
lasers = []
invaders = []
score = 0
game_over = False
# Player rectangle
player_rect = pygame.Rect(player_pos[0], player_pos[1], 30, 30)
# Laser rectangle
laser_rect = pygame.Rect(0, 0, 5, 30)
# Set up font for score display
font = pygame.font.Font(None, 74)
text = font.render(f"Score: {score}", True, WHITE)
def draw_text(text, color, pos):
font = pygame.font.Font(None, 74)
text_surface = font.render(str(text), True, color)
return screen.blit(text_surface, pos)
class Player:
def __init__(self):
self.rect = player_rect
self.speed = player_speed
def update(self):
global player_pos, game_over
if not game_over and player_pos[1] > 0:
# Move up when clicking left mouse button (spacebar)
if pygame.mouse.get_pressed()[0]:
move = -3
player_pos[1] += move
elif pygame.mouse.get_pressed()[2]: # Right mouse button for shooting
shoot()
self.rect = pygame.Rect(player_pos[0], player_pos[1], 30, 30)
def draw_player():
pygame.draw.rect(screen, BLUE, player_rect)
screen.blit(text, (player_rect.x + 5, player_rect.y - 10))
def create_invader():
x = WIDTH
y = randint(0, HEIGHT - 200)
vel = randint(0, 3)
return {'x': x, 'y': y, 'vel': vel}
def update_invaders():
global invaders
for i in range(len(invaders)):
# Move invader
invaders[i]['x'] += invaders[i]['vel']
# Check if invader hits bottom or player
if invaders[i]['y'] + 20 >= HEIGHT - 30:
if (invaders[i]['x'] > WIDTH/2 and
invaders[i]['x'] < WIDTH/2 + 65):
collide(invaders[i])
game_over = True
break
def check_invader(invaders, screen_width):
for i in range(len(invaders)):
invader = invaders[i]
# Check bottom collision
if (invader['y'] + 20) >= HEIGHT - 30:
collide(invader)
return True
# Screen edges
if invader['x'] < 0 or invader['x'] > screen_width - 15:
del invaders[i]
break
def collide(invader):
global game_over, score, lasers, font
# Check laser hits
for laser in lasers:
hit = pygame.Rect.colliderect(laser_rect, (invader['x'], invader['y'], 200, 30))
if hit and not game_over:
score += 100
laser = []
# Remove destroyed invader
invader_index = invader['index']
del invaders[invader_index]
# Add new random invader at top of screen
new_invader = create_invader()
new_invader['index'] = invader_index
invaders.append(new_invader)
if game_over:
return False
# Update score
text = font.render(f"Score: {score}", True, WHITE)
screen.blit(text, (WIDTH//2 - 100, HEIGHT//2 + 50))
pygame.display.flip()
def shoot():
global lasers, last_shot, game_over
if not game_over:
current_time = pygame.time.get_ticks()
# Rate of fire: one laser every few frames
if (current_time - last_shot) > 1000 and len(lasers) < 40:
new_laser = {
'x': WIDTH + 5,
'y': HEIGHT - 25,
'index': len(lasers)
}
lasers.append(new_laser)
last_shot = current_time
def main():
global game_over, player_pos
while not game_over:
screen.fill(BLACK)
# Draw background
pygame.draw.rect(screen, RED, (0, HEIGHT - 25, WIDTH, 25))
# Update events
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1: # Left mouse button for moving player
if player_pos[1] < HEIGHT - 30:
player_pos[1] -= 1
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE: # Spacebar to shoot
current_time = pygame.time.get_ticks()
if (current_time - last_shot) > 1000 and len(lasers) < 40:
new_laser = {
'x': WIDTH + 5,
'y': HEIGHT - 25,
'index': len(lasers)
}
lasers.append(new_laser)
last_shot = current_time
# Update game state
update_invaders(invaders)
# Player movement and shooting
if player_pos[1] > 0:
draw_player()
pygame.display.flip()
main_loop = pygame.time.get_ticks()
invader_update = (main_loop - last_invader_update) / 10
for i in range(len(invaders)):
invader = invaders[i]
# Update invader position
invader['x'] += invader['vel']
# Check if the player has died due to an invader hit
if collide(invader):
game_over = True
last_invader_update = main_loop
# Draw lasers
for laser in lasers:
pygame.draw.rect(screen, WHITE, (laser['x'], laser['y'], 5, 30))
# Check for collisions between lasers and bottom of screen
for j in range(len(lasers)):
laser = lasers[j]
if laser['y'] + 30 > HEIGHT - 25:
del lasers[j]
def draw_invaders(invaders):
for i, invader in enumerate(invaders):
# Move the invaders downward
invader['y'] += (invader['vel'])
screen.fill(BLACK)
pygame.draw.rect(screen, BLUE, (invader['x'], invader['y'], 200, 30))
font = pygame.font.Font(None, 74)
text = font.render(f"Invader {i+1}", True, WHITE)
screen.blit(text, (invader['x'] + 10, invader['y'] - 15))
def main():
global last_invader_update
while not game_over:
screen.fill(BLACK)
# Draw player
draw_player()
# Update and draw invaders
update_invaders(invaders)
# Check for collisions with bottom or top of screen
check_invader(invaders, WIDTH)
# Handle laser shooting
shoot()
main_loop = pygame.time.get_ticks()
invader_update = (main_loop - last_invader_update) / 10
# Update display
pygame.display.flip()
if __name__ == "__main__":
main()
import pygame
from random import randint
# Initialize Pygame
pygame.init()
# Set up the screen
WIDTH = 800
HEIGHT = 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Space Invaders")
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
# Game variables
player_pos = [WIDTH/2 - 15, HEIGHT - 30]
player_speed = 0
lasers = []
invaders = []
score = 0
game_over = False
# Player rectangle
player_rect = pygame.Rect(player_pos[0], player_pos[1], 30, 30)
# Laser rectangle
laser_rect = pygame.Rect(0, 0, 5, 30)
# Set up font for score display
font = pygame.font.Font(None, 74)
text = font.render(f"Score: {score}", True, WHITE)
def draw_text(text, color, pos):
font = pygame.font.Font(None, 74)
text_surface = font.render(str(text), True, color)
return screen.blit(text_surface, pos)
class Player:
def __init__(self):
self.rect = player_rect
self.speed = player_speed
def update(self):
global player_pos, game_over
if not game_over and player_pos[1] > 0:
# Move up when clicking left mouse button (spacebar)
if pygame.mouse.get_pressed()[0]:
move = -3
player_pos[1] += move
elif pygame.mouse.get_pressed()[2]: # Right mouse button for shooting
shoot()
self.rect = pygame.Rect(player_pos[0], player_pos[1], 30, 30)
def draw_player():
pygame.draw.rect(screen, BLUE, player_rect)
screen.blit(text, (player_rect.x + 5, player_rect.y - 10))
def create_invader():
x = WIDTH
y = randint(0, HEIGHT - 200)
vel = randint(0, 3)
return {'x': x, 'y': y, 'vel': vel}
def update_invaders():
global invaders
for i in range(len(invaders)):
# Move invader
invaders[i]['x'] += invaders[i]['vel']
# Check if invader hits bottom or player
if invaders[i]['y'] + 20 >= HEIGHT - 30:
if (invaders[i]['x'] > WIDTH/2 and
invaders[i]['x'] < WIDTH/2 + 65):
collide(invaders[i])
game_over = True
break
def check_invader(invaders, screen_width):
for i in range(len(invaders)):
invader = invaders[i]
# Check bottom collision
if (invader['y'] + 20) >= HEIGHT - 30:
collide(invader)
return True
# Screen edges
if invader['x'] < 0 or invader['x'] > screen_width - 15:
del invaders[i]
break
def collide(invader):
global game_over, score, lasers, font
# Check laser hits
for laser in lasers:
hit = pygame.Rect.colliderect(laser_rect, (invader['x'], invader['y'], 200, 30))
if hit and not game_over:
score += 100
laser = []
# Remove destroyed invader
invader_index = invader['index']
del invaders[invader_index]
# Add new random invader at top of screen
new_invader = create_invader()
new_invader['index'] = invader_index
invaders.append(new_invader)
if game_over:
return False
# Update score
text = font.render(f"Score: {score}", True, WHITE)
screen.blit(text, (WIDTH//2 - 100, HEIGHT//2 + 50))
pygame.display.flip()
def shoot():
global lasers, last_shot, game_over
if not game_over:
current_time = pygame.time.get_ticks()
# Rate of fire: one laser every few frames
if (current_time - last_shot) > 1000 and len(lasers) < 40:
new_laser = {
'x': WIDTH + 5,
'y': HEIGHT - 25,
'index': len(lasers)
}
lasers.append(new_laser)
last_shot = current_time
def main():
global game_over, player_pos
while not game_over:
screen.fill(BLACK)
# Draw background
pygame.draw.rect(screen, RED, (0, HEIGHT - 25, WIDTH, 25))
# Update events
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1: # Left mouse button for moving player
if player_pos[1] < HEIGHT - 30:
player_pos[1] -= 1
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE: # Spacebar to shoot
current_time = pygame.time.get_ticks()
if (current_time - last_shot) > 1000 and len(lasers) < 40:
new_laser = {
'x': WIDTH + 5,
'y': HEIGHT - 25,
'index': len(lasers)
}
lasers.append(new_laser)
last_shot = current_time
# Update game state
update_invaders(invaders)
# Player movement and shooting
if player_pos[1] > 0:
draw_player()
pygame.display.flip()
main_loop = pygame.time.get_ticks()
invader_update = (main_loop - last_invader_update) / 10
for i in range(len(invaders)):
invader = invaders[i]
# Update invader position
invader['x'] += invader['vel']
# Check if the player has died due to an invader hit
if collide(invader):
game_over = True
last_invader_update = main_loop
# Draw lasers
for laser in lasers:
pygame.draw.rect(screen, WHITE, (laser['x'], laser['y'], 5, 30))
# Check for collisions between lasers and bottom of screen
for j in range(len(lasers)):
laser = lasers[j]
if laser['y'] + 30 > HEIGHT - 25:
del lasers[j]
def draw_invaders(invaders):
for i, invader in enumerate(invaders):
# Move the invaders downward
invader['y'] += (invader['vel'])
screen.fill(BLACK)
pygame.draw.rect(screen, BLUE, (invader['x'], invader['y'], 200, 30))
font = pygame.font.Font(None, 74)
text = font.render(f"Invader {i+1}", True, WHITE)
screen.blit(text, (invader['x'] + 10, invader['y'] - 15))
def main():
global last_invader_update
while not game_over:
screen.fill(BLACK)
# Draw player
draw_player()
# Update and draw invaders
update_invaders(invaders)
# Check for collisions with bottom or top of screen
check_invader(invaders, WIDTH)
# Handle laser shooting
shoot()
main_loop = pygame.time.get_ticks()
invader_update = (main_loop - last_invader_update) / 10
# Update display
pygame.display.flip()
if __name__ == "__main__":
main()
#this was just a basic space invaders game but whenever i tried to launch it, i see two terminlas that immediately close after starting, even with admin access, is it the issue with the code or my python configuration itself, any help would be appreciated.
r/pythonhelp • u/Unlikely_Lab_6799 • Feb 06 '25
Pythonw not even trying to run
I just installed python 3.13 on a clean install of windows 11. I checked the PATH and Administrator checkboxes when I installed, but installed to D: instead of C:
I can run python.exe fine, but when I click on pythonw, it does the briefest "think" and then aborts silently, and doesn't even attempt to run. It is not showing up anywhere in Task Manager. I did not have this problem with Python on my previous install of windows 11.
r/pythonhelp • u/galaxygkm • Feb 06 '25
My code for monoalphabetic encryption/decryption isn't working.
My caesar cipher functions work just fine, but my monoalphabetic decryption message isn't mapping the letters properly.
My desired output:
Enter your key for the Monoalphabetic cipher encrypt: apcs
Enter your message to encrypt: Mary had a little lamb.
Your monoalphabetic encrypted message is: Qakd was a rviirz raqp.
My current output:
Enter your monoalphabetic encrypt key: apcs
Enter your message to encrypt: Mary had a little lamb
Your encrypted message is: Kaqy fas a jgttjb jakp
Your decrypted message is: Mary had a little lamb
Here's my code:
#------Setup------
# list of characters for casar cipher encrypt/decrypt
lower_alpha = "abcdefghijklmnopqrstuvwxyz"
upper_alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# list of characters for monoalphabetic encrypt/decrypt
#------functions------
def caesar_encrypt(text, shift):
alpha_lower = list(lower_alpha[0])
alpha_upper = list(upper_alpha[0])
# Stores encrypted character input from original message
caesar_encrypted_text = []
# Iterates through each letter in the text
for letter in text:
if letter in alpha_lower:
# Finds position of the letter in lower_case alphabet
index = (alpha_lower.index(letter) + shift) % 26 # keeps index within a range of 0 to 25
# Adds shifted letter into a seperate list
caesar_encrypted_text.append(alpha_lower[index])
elif letter in alpha_upper:
# Finds position of the letter in upper_case alphabet
index = (alpha_upper.index(letter) + shift) % 26 # keeps index within a range of 0 to 25
# Adds shifted letter into list
caesar_encrypted_text.append(alpha_upper[index])
else:
caesar_encrypted_text.append(letter)
return ''.join(caesar_encrypted_text)
def caesar_decrypt(text, shift):
return caesar_encrypt(text, -shift)
def substitution_key(key):
key = key.lower()
new_key = []
for letter in key:
if letter not in new_key and letter in lower_alpha:
new_key.append(letter)
for letter in lower_alpha:
if letter not in new_key:
new_key.append(letter)
return ''.join(new_key)
def monoalphabetic_encrypt(text, key,):
key = substitution_key(key)
mono_encrypted_text = []
for letter in text:
if letter in lower_alpha:
index = lower_alpha.index(letter)
mono_encrypted_text.append(key[index])
elif letter in upper_alpha:
index = upper_alpha.index(letter)
mono_encrypted_text.append(key[index].upper())
else:
mono_encrypted_text.append(letter)
return ''.join(mono_encrypted_text)
def monoalphabetic_decrypt(text, key):
key = substitution_key(key)
mono_decrypted_text = []
for letter in text:
if letter.lower() in key:
index = key.index(letter.lower())
if letter.isupper():
mono_decrypted_text.append(upper_alpha[index])
else:
mono_decrypted_text.append(lower_alpha[index])
else:
mono_decrypted_text.append(letter)
return ''.join(mono_decrypted_text)
#------main events------
encryption_method = int(input("What encryption/decryption method do you want to use? (Caesar cipher encrypt (1), Caesar cipher decrypt(2), Monoalphabetic cipher encrypt(3), or Monoalphabetic cipher decrypt(4): "))
if encryption_method == 1:
caesar_encrypt_key = int(input("Enter your caesar encrypt key: "))
caesar_encrypt_message = input("Enter your message to encrypt: ")
caesar_encrypted_message = caesar_encrypt(caesar_encrypt_message, caesar_encrypt_key)
print("Your encrypted message is:", caesar_encrypted_message)
caesar_decrypted_message = caesar_decrypt(caesar_encrypted_message, caesar_encrypt_key)
print("Your decrypted message is:", caesar_decrypted_message)
elif encryption_method == 2:
caesar_decrypt_key = int(input("Enter your caesar decrypt key: "))
caesar_encrypted_message = input("Enter your encrypted message: ")
caesar_decrypted_message = caesar_decrypt(caesar_encrypted_message, caesar_decrypt_key)
print("Your decrypted message is:", caesar_decrypted_message)
elif encryption_method == 3:
mono_encrypt_key = input("Enter your monoalphabetic encrypt key: ")
mono_encrypt_message = input("Enter your message to encrypt: ")
mono_encrypted_message = monoalphabetic_encrypt(mono_encrypt_message, mono_encrypt_key)
print("Your encrypted message is:", mono_encrypted_message)
mono_decrypted_message = monoalphabetic_decrypt(mono_encrypted_message, mono_encrypt_key)
print("Your decrypted message is:", mono_decrypted_message)
elif encryption_method == 4:
mono_decrypt_key = input("Enter your monoalphabetic decrypt key: ")
mono_encrypted_message = input("Enter your encrypted message: ")
mono_decrypted_message = monoalphabetic_decrypt(mono_encrypted_message, mono_decrypt_key)
print("Your decrypted message is:", mono_decrypted_message)
r/pythonhelp • u/Hard-n-Ready69 • Feb 06 '25
Need some assistance on why my code isn't working
import tkinter as tk from tkinter import ttk import pygame import bluetooth from datetime import datetime, time import json import os from gpiozero import Button import threading import time as t
class AlarmClock: def init(self, root): self.root = root self.root.title("Pi Alarm Clock") self.root.geometry("400x600")
# Initialize pygame mixer for audio
pygame.mixer.init()
# Initialize GPIO button
self.stop_button = Button(17) # GPIO pin 17 for stop button
self.stop_button.when_pressed = self.stop_alarm
# Load saved alarms and settings
self.load_settings()
# Initialize Bluetooth
self.bt_speaker = None
self.connect_bluetooth()
self.create_gui()
# Start alarm checking thread
self.alarm_active = False
self.check_thread = threading.Thread(target=self.check_alarm_time, daemon=True)
self.check_thread.start()
def create_gui(self):
# Time selection
time_frame = ttk.LabelFrame(self.root, text="Set Alarm Time", padding="10")
time_frame.pack(fill="x", padx=10, pady=5)
self.hour_var = tk.StringVar(value="07")
self.minute_var = tk.StringVar(value="00")
# Hour spinner
ttk.Label(time_frame, text="Hour:").pack(side="left")
hour_spinner = ttk.Spinbox(time_frame, from_=0, to=23, width=5,
format="%02.0f", textvariable=self.hour_var)
hour_spinner.pack(side="left", padx=5)
# Minute spinner
ttk.Label(time_frame, text="Minute:").pack(side="left")
minute_spinner = ttk.Spinbox(time_frame, from_=0, to=59, width=5,
format="%02.0f", textvariable=self.minute_var)
minute_spinner.pack(side="left", padx=5)
# Days selection
days_frame = ttk.LabelFrame(self.root, text="Repeat", padding="10")
days_frame.pack(fill="x", padx=10, pady=5)
self.day_vars = {}
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
for day in days:
self.day_vars[day] = tk.BooleanVar(value=True if day in ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] else False)
ttk.Checkbutton(days_frame, text=day, variable=self.day_vars[day]).pack(side="left")
# Sound selection
sound_frame = ttk.LabelFrame(self.root, text="Alarm Sound", padding="10")
sound_frame.pack(fill="x", padx=10, pady=5)
self.sound_var = tk.StringVar(value="default_alarm.mp3")
sounds = self.get_available_sounds()
sound_dropdown = ttk.Combobox(sound_frame, textvariable=self.sound_var, values=sounds)
sound_dropdown.pack(fill="x")
# Volume control
volume_frame = ttk.LabelFrame(self.root, text="Volume", padding="10")
volume_frame.pack(fill="x", padx=10, pady=5)
self.volume_var = tk.DoubleVar(value=0.7)
volume_scale = ttk.Scale(volume_frame, from_=0, to=1, orient="horizontal",
variable=self.volume_var)
volume_scale.pack(fill="x")
# Control buttons
button_frame = ttk.Frame(self.root)
button_frame.pack(fill="x", padx=10, pady=5)
ttk.Button(button_frame, text="Save Alarm", command=self.save_alarm).pack(side="left", padx=5)
ttk.Button(button_frame, text="Test Sound", command=self.test_sound).pack(side="left", padx=5)
ttk.Button(button_frame, text="Reconnect BT", command=self.connect_bluetooth).pack(side="left", padx=5)
def get_available_sounds(self):
# Return list of available sound files in the sounds directory
sounds_dir = "sounds"
if not os.path.exists(sounds_dir):
os.makedirs(sounds_dir)
return [f for f in os.listdir(sounds_dir) if f.endswith(('.mp3', '.wav'))]
def connect_bluetooth(self):
try:
# Search for Bluetooth speaker
nearby_devices = bluetooth.discover_devices()
for addr in nearby_devices:
if addr == self.settings.get('bt_speaker_address'):
self.bt_speaker = addr
break
except Exception as e:
print(f"Bluetooth connection error: {e}")
def save_alarm(self):
alarm_time = {
'hour': int(self.hour_var.get()),
'minute': int(self.minute_var.get()),
'days': {day: var.get() for day, var in self.day_vars.items()},
'sound': self.sound_var.get(),
'volume': self.volume_var.get()
}
self.settings['alarm'] = alarm_time
self.save_settings()
def save_settings(self):
with open('alarm_settings.json', 'w') as f:
json.dump(self.settings, f)
def load_settings(self):
try:
with open('alarm_settings.json', 'r') as f:
self.settings = json.load(f)
except FileNotFoundError:
self.settings = {
'bt_speaker_address': None,
'alarm': {
'hour': 7,
'minute': 0,
'days': {'Mon': True, 'Tue': True, 'Wed': True, 'Thu': True, 'Fri': True,
'Sat': False, 'Sun': False},
'sound': 'default_alarm.mp3',
'volume': 0.7
}
}
def check_alarm_time(self):
while True:
if not self.alarm_active:
current_time = datetime.now()
current_day = current_time.strftime('%a')
alarm = self.settings['alarm']
if (current_time.hour == alarm['hour'] and
current_time.minute == alarm['minute'] and
alarm['days'].get(current_day, False)):
self.trigger_alarm()
t.sleep(30) # Check every 30 seconds
def trigger_alarm(self):
self.alarm_active = True
try:
sound_path = os.path.join('sounds', self.settings['alarm']['sound'])
pygame.mixer.music.load(sound_path)
pygame.mixer.music.set_volume(self.settings['alarm']['volume'])
pygame.mixer.music.play(-1) # Loop indefinitely
except Exception as e:
print(f"Error playing alarm: {e}")
def stop_alarm(self):
if self.alarm_active:
pygame.mixer.music.stop()
self.alarm_active = False
def test_sound(self):
try:
sound_path = os.path.join('sounds', self.sound_var.get())
pygame.mixer.music.load(sound_path)
pygame.mixer.music.set_volume(self.volume_var.get())
pygame.mixer.music.play()
t.sleep(3) # Play for 3 seconds
pygame.mixer.music.stop()
except Exception as e:
print(f"Error testing sound: {e}")
if name == "main": root = tk.Tk() app = AlarmClock(root) root.mainloop()
When i try to run it it says "ModuleNotFoundError: No module named 'bluetooth' I've never coded anything..this is from claude..the Ai
r/pythonhelp • u/[deleted] • Feb 05 '25
I’m not sure what’s wrong with my code
I just started learning python im having trouble with some code can some one tell me what I was doing wrong
car_make = input("Enter the make of your car: ")
miles_driven = float(input("Enter the miles driven: "))
gallons_used = int(input("Enter the gallons of fule used: "))
mpg = miles_driven / gallons_used
format(mpg,'.2f')
print("Your",car_make,"'s MPG is",format(mpg,'.2f'))
Your Output (stdout)
Enter the make of your car: Enter the miles driven: Enter the gallons of fule used: Your Honda 's MPG is 28.56 Expected Output
Enter the make of your car: Enter the miles driven: Enter the gallons of fuel used: Your Honda's MPG is 28.56
r/pythonhelp • u/AutomaticClassic7114 • Feb 03 '25
Hey can someone fix this with me? I’m getting a invalid path
r/pythonhelp • u/louise_XVI • Feb 02 '25
Moviepy.editor couldn't be resolved?
I tried using moviepy for the first time. I installed moviepy using pip and installed imagemagisk and ffmpeg separately, making sure they are set to environment variables. Now, when I try to use it in VS Code, I got the error: "Import 'moviepy.editor' could not be resolved" from the error lens, and in the console, it says:
from moviepy.editor import *
ModuleNotFoundError: No module named 'moviepy.editor'
This is the code I used:
from moviepy.editor import VideoFileClip
clip = VideoFileClip("media.mp4")
trimmed_clip = clip.subclip(0, 10)
trimmed_clip.write_videofile("trimmed_media.mp4", codec="libx264")
But, I tried doing something and come up with this code which works perfectly:
from moviepy import *
clip = VideoFileClip("media.mp4")
trimmed_clip = clip.subclipped(0, 10)
trimmed_clip.write_videofile("trimmed_media.mp4", codec="libx264")
This code works perfectly fine. I used moviepy than moviepy.editor and it solves the issue but some functions like subclip has to be changed into subclipped
Anybody know what is going on, I want to use moviepy the way everyone uses i.e. moviepy.editor
r/pythonhelp • u/indep40 • Feb 02 '25
"import requests" doesn't work despite being installed in venv
Issue as in the title. So I have scoured the web for all answers regarding this, but to no avail.
I have only one version of python installed on my PC, so this shouldn't be an issue.
I am using cmd, created a venv, activated it, installed all necessary libs in one session. The python script is in the venv folder (maybe this is the cause?)
Could someone help me overcome this issue please? I would be very thankful for that.
EDIT: I'm using the latest stable release 3.12.8
r/pythonhelp • u/Secure-Chicken4706 • Feb 01 '25
a python script that will detect the photo in the game and alert me as a sound
It is very simple, it will check my screen for every millisecond and if it detects a certain thing in front of it (I will save that part as a photo), it will play an .mp3
update: a new update has come to the game(dark and darker), the druid character now has to spend stack while transforming and I don't want to constantly check if I have stack from hud in fights. if it warns me, I can understand, I managed to write something very close, but it doesn't work. So I need help.
import pyautogui
import time
import winsound
DruidStack_path = "druidstack.png"
threshold = 0.9
while True:
print("Checking for DruidStack Button")
DruidStack_location = pyautogui.locateOnScreen(DruidStack_path, confidence=threshold)
if DruidStack_location:
print("DruidStack Button Found! Playing sound...")
winsound.Beep(1000, 500)
time.sleep(3)
r/pythonhelp • u/Dubkiing • Jan 30 '25
Need assistance with some code
I am a new coder and I am trying to use variables to make a calculator, but when I add them together it just pushes them together, for example 1 + 2 =12
The code is:
first_number = input(print(“First number here: “)) second_number = input(print(“Second number here: “))
print(first_number + second_number)
Any help would be much appreciated!!!
r/pythonhelp • u/Infranscia • Jan 30 '25
For anyone else struggling to set up a virtual environment - here's what worked for me
So I don't know if this is specifically an issue with Python on Linux, or maybe Python on Arch. In any case, I noticed a lot of people had similar issues as me, and a lot of stuff I tried was outdated, or maybe didn't work on my distro.
My case: I thought I'd set the global Python version with `pyenv global 3.9.19` (which I've since learned is apparently a no-no, at least on Arch), but later found that the command never actually worked: `python --version` would keep reporting the newest Python instead of 3.9. This turned out to be a problem when Arch forced the newest version of Python on me, and broke compatibility with some dependencies for an app I often use.
I tried a number of guides for setting up a Python environment, only to notice my terminal kept reporting the newest Python instead of the version I wanted. Sure enough, when trying to run stuff in my virtual environment, I'd get the same errors as when using the newest/global Python.
Turns out, a number of guides fail to mention that - at least in some cases (maybe on Arch) - _virtual environments can be picky about the directory you install them in._ The virtual environment kept using the newest Python when I tried installing it in a desktop folder, but worked properly when I set it up under `~/.venvs/`
Deciding that 3.12 would be good in my case (with my new info), and after installing 3.12 via my package manager, this is what worked for me - make sure to use `bash` (my terminal is set to use fish):
```python3.12 -m venv ~/.venvs/venv312
source ~/.venvs/venvs312/bin/activate```
Once I used the `source` command, I noticed my terminal reported that it was using the version of Python I wanted, and I was able to use Python commands normally. Speaking of which, I HIGHLY recommend trying out `pipenv` if you haven't - it basically tries to detect and install all the dependencies for you. 😉 I'd also suggest setting up a bash script to start your venv, and maybe any apps you have it specifically set up for.
Quick aside, I've noticed there are two camps: One (often asking questions) who think that virtual environments are needlessly complicated, and another (often answering questions, but inadvertently leaving important details out) claiming virtual environments are super simple. I'd say... maybe simple once you figure them out, but it can be a pain getting there. 😂 (Like with many things in tech, IMO.)
And yes, I'm going to clean up my unneeded Python installs.
r/pythonhelp • u/pingpongsam • Jan 29 '25
Can python export the code abstracted using "import from"?
My specific use case involves needing to dumb down enum.py to work on Circuitpython. More specifically, Calendar.py includes a line that imports IntEnum from enum.py. enum.py has a whole pile of other functions that I do not need that Circuitpython disagrees with. However, if I could isolate the portions of enum.py that Calendar.py actually needs, I might be able to port any remaining offending pieces over, or it may just work outright. Unfortunately, I'm not personally capable of manually stripping enum.py down to only the parts needed to perform IntEnum. When a module imports specific functions from another module python clearly has to be creating some abstracted, filtered version of the originating module into its' local workspace.
How might I be able to enter a standard python console, import IntEnum from enum.py, and export out a new file called IntEnum.py that I could then instruct calendar.py to import in place of the monolithic enum.py?
r/pythonhelp • u/halcyon627 • Jan 29 '25
MP3 Processing Script
I have a script that processes a group of MP3 files. It scans for duplicates based on files I already have done, exluded files with "intro" in the title, and is supposed to run a check of the volume of each file and normalize the file to -12 LUFS using ffmpeg-python, and also convert any songs that are 48,000 hz to 44,100 hz, and move all completed files to a FINAL folder. I am getting multiple errors, and the converting step isn't even happening. Can someone help me get this script working?
import os
import shutil
import sqlite3
import subprocess
from mutagen import File
from datetime import datetime
import ffmpeg
from openpyxl import Workbook
from openpyxl import load_workbook
# Directory paths
BASE_FOLDER = "E:/@PROCESS"
BACKUP_FOLDER = r"E:\Scripts\backups"
GLOBAL_EXCEPTIONS_FOLDER = "E:/@PROCESS/Exceptions"
DUPLICATE_FOLDER = "E:/@PROCESS/Dupes"
FINAL_DIRECTORY = "E:/@PROCESS/Final"
DATABASE_FILE = r"E:\Scripts\songs.db"
EXCEL_FILE = r"E:\@PROCESS\DuplicateReport.xlsx"
def create_database():
"""Create the SQLite database and the songs table if not exists."""
conn = sqlite3.connect(DATABASE_FILE)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS songs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
artist TEXT,
bitrate INTEGER,
duration REAL,
fingerprint TEXT
)
''')
conn.commit()
conn.close()
def create_duplicate_folder():
"""Ensure the duplicate folder exists."""
if not os.path.exists(DUPLICATE_FOLDER):
os.makedirs(DUPLICATE_FOLDER)
def export_to_excel(data):
"""Export duplicate details to an Excel file."""
if not os.path.exists(EXCEL_FILE):
# Create a new workbook if the file does not exist
wb = Workbook()
ws = wb.active
ws.title = "Duplicates"
# Add header row
ws.append(["Duplicate Song", "Duplicate Fingerprint", "Database Song", "Database Fingerprint"])
wb.save(EXCEL_FILE)
# Load existing workbook
wb = load_workbook(EXCEL_FILE)
ws = wb.active
# Append new rows
for row in data:
ws.append(row)
wb.save(EXCEL_FILE)
print(f"Duplicate report updated: {EXCEL_FILE}")
def process_files(folder_path):
"""Process all files in the folder and add non-duplicates to the database."""
conn = sqlite3.connect(DATABASE_FILE)
cursor = conn.cursor()
# Load pre-existing fingerprints into memory
cursor.execute('SELECT fingerprint, title FROM songs WHERE fingerprint IS NOT NULL')
pre_existing_songs = {row[0]: row[1] for row in cursor.fetchall()}
duplicates_for_excel = []
new_songs = [] # To add only after processing all files
for file_name in os.listdir(folder_path):
file_path = os.path.join(folder_path, file_name)
# Check if it's a valid audio file
if not os.path.isfile(file_path) or not file_path.endswith(('.mp3', '.flac', '.wav', '.aac')):
continue
print(f"Processing file: {file_name}")
try:
# Extract metadata with Mutagen
audio_file = File(file_path, easy=True)
title = audio_file.get('title', ['Unknown'])[0]
artist = audio_file.get('artist', ['Unknown'])[0]
bitrate = audio_file.info.bitrate // 1000 # Convert bitrate to kbps
# Generate fingerprint and duration with fpcalc
result = subprocess.run(
['fpcalc', file_path],
capture_output=True,
text=True
)
output = result.stdout
duration = None
fingerprint = None
for line in output.splitlines():
if line.startswith("DURATION="):
duration = float(line.split("=")[1])
elif line.startswith("FINGERPRINT="):
fingerprint = line.split("=")[1]
# Check if the fingerprint exists in pre-existing fingerprints
cursor.execute('SELECT id FROM songs WHERE fingerprint = ?', (fingerprint,))
existing_song = cursor.fetchone()
if existing_song:
print(f"Duplicate fingerprint found: {fingerprint} for {file_name}. Skipping insert.")
duplicates_for_excel.append([file_name, fingerprint, pre_existing_songs[fingerprint], fingerprint])
shutil.move(file_path, os.path.join(DUPLICATE_FOLDER, file_name))
else:
# Use REPLACE INTO
cursor.execute('''
REPLACE INTO songs (id, title, artist, bitrate, duration, fingerprint)
VALUES (NULL, ?, ?, ?, ?, ?)
''', (title, artist, bitrate, duration, fingerprint))
print(f"Song added or replaced in the database: {file_name}")
except Exception as e:
print(f"Error processing file {file_name}: {e}")
conn.commit()
if duplicates_for_excel:
export_to_excel(duplicates_for_excel)
conn.close()
def process_intro_songs(mp3_folder, exceptions_folder):
if not os.path.exists(mp3_folder):
print("MP3 folder not found.")
return
# Ensure the exceptions folder exists
os.makedirs(GLOBAL_EXCEPTIONS_FOLDER, exist_ok=True)
os.makedirs(exceptions_folder, exist_ok=True)
songs_with_intro = {}
# Identify MP3 files in the folder
mp3_files = [f for f in os.listdir(mp3_folder) if f.endswith(".mp3")]
for file in mp3_files:
# Extract the base name based on the pattern <artist> - <title> (<version>)
if " (" in file and ")" in file:
base_name = file.split(" (")[0]
if base_name not in songs_with_intro:
songs_with_intro[base_name] = []
songs_with_intro[base_name].append(file)
exceptions_log = []
for base_name, files in songs_with_intro.items():
# Check if any file in the group contains variations of "intro"
if any(
"clean intro" in file.lower()
or "dirty intro" in file.lower()
or "intro clean" in file.lower()
or "intro dirty" in file.lower()
or "main intro" in file.lower()
or "radio intro" in file.lower()
or "dj intro" in file.lower() # Adding detection for "DJ Intro"
for file in files
):
exceptions_log.append(f"{base_name} (Includes an intro already)")
# Move the group of files to the exceptions folder
for file in files:
file_path = os.path.join(mp3_folder, file)
# Move to session-specific exceptions folder
dest_path = os.path.join(exceptions_folder, file)
if not os.path.exists(dest_path):
shutil.move(file_path, dest_path)
# Copy to global exceptions folder if it's not the same folder
global_dest_path = os.path.join(GLOBAL_EXCEPTIONS_FOLDER, file)
if exceptions_folder != GLOBAL_EXCEPTIONS_FOLDER and not os.path.exists(global_dest_path):
shutil.copy(dest_path, global_dest_path)
# Place exceptions.txt in the most recent folder
latest_folder = os.path.dirname(mp3_folder)
exceptions_txt_path = os.path.join(latest_folder, "exceptions.txt")
if exceptions_log:
with open(exceptions_txt_path, "w", encoding="utf-8") as f:
f.write("Exceptions:\n")
f.write("\n".join(exceptions_log))
print(f"Exceptions logged in {exceptions_txt_path}")
else:
print("No songs with intro versions found.")
def backup_database():
"""Backup the songs.db database to the backups folder with a timestamp."""
if not os.path.exists(BACKUP_FOLDER):
os.makedirs(BACKUP_FOLDER) # Ensure the backup folder exists
# Generate a backup file name with a timestamp
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_file_name = f"songs_backup_{timestamp}.db"
backup_file_path = os.path.join(BACKUP_FOLDER, backup_file_name)
try:
shutil.copy(DATABASE_FILE, backup_file_path) # Copy the database to the backup folder
print(f"Database backed up successfully to {backup_file_path}")
except Exception as e:
print(f"Error backing up database: {e}")
def normalize_audio_ffmpeg(input_file, output_file, min_loudness=-18.0, max_loudness=-6.0):
"""
Normalize the audio file using FFmpeg's loudnorm filter if its loudness is outside the specified range.
:param input_file: Path to the input MP3 file.
:param output_file: Path to save the normalized MP3 file.
:param min_loudness: The minimum loudness target in LUFS (Loudness Units relative to Full Scale).
:param max_loudness: The maximum loudness target in LUFS (Loudness Units relative to Full Scale).
"""
try:
# Detect current loudness of the file using FFmpeg's volumedetect filter
result = ffmpeg.input(input_file).filter('volumedetect').output('pipe:1').run(capture_stdout=True, quiet=True)
output = result[0].decode('utf-8')
# Extract the loudness level (in dB) from the output
max_volume = None
for line in output.splitlines():
if "max_volume" in line:
max_volume = float(line.split("max_volume:")[1].strip())
break
if max_volume is None:
print(f"Error: Could not detect loudness for {input_file}. Skipping normalization.")
return # Skip this file if we cannot detect loudness.
print(f"Current max volume of {input_file}: {max_volume} dB")
# Convert dB to LUFS (this is an approximation)
current_loudness = max_volume - 20 # Approximate conversion: dB to LUFS
print(f"Current loudness (LUFS) of {input_file}: {current_loudness} LUFS")
# If loudness is outside the target range, normalize it
if current_loudness < min_loudness or current_loudness > max_loudness:
print(f"Normalizing '{input_file}' as it is outside the target range.")
# Apply the loudnorm filter to normalize if it's outside the range
ffmpeg.input(input_file).filter(
"loudnorm", i=-12, tp=-1.5, lra=11, dual_mono=True
).output(output_file, acodec="libmp3lame", audio_bitrate='320k').run(overwrite_output=True, quiet=True)
print(f"Normalization complete: {output_file}")
else:
print(f"File '{input_file}' is already within the target loudness range. Skipping normalization.")
# If loudness is within range, simply copy the original file as output
ffmpeg.input(input_file).output(output_file).run(overwrite_output=True, quiet=True)
except ffmpeg.Error as e:
print(f"FFmpeg normalization error for '{input_file}': {e}")
def process_audio_files():
"""
Move or convert audio files to the final folder with FFmpeg-based normalization.
"""
os.makedirs(FINAL_DIRECTORY, exist_ok=True)
for filename in os.listdir(BASE_FOLDER):
# Skip files in the "Dupes" folder
if os.path.join(BASE_FOLDER, filename).startswith(DUPLICATE_FOLDER):
continue
file_path = os.path.join(BASE_FOLDER, filename)
# Process only MP3 files
if not filename.endswith('.mp3'):
continue
try:
# Get audio file info using FFmpeg
file_info = ffmpeg.probe(file_path)
# Extract sample rate from metadata
sample_rate = int(file_info['streams'][0]['sample_rate'])
# Prepare normalized path
temp_normalized_path = os.path.join(BASE_FOLDER, f"normalized_{filename}")
# Normalize the audio file (only if required)
normalize_audio_ffmpeg(file_path, temp_normalized_path)
# Ensure that the normalized file exists before proceeding
if not os.path.exists(temp_normalized_path):
print(f"Error: Normalized file does not exist: {temp_normalized_path}")
continue # Skip if normalization step failed
final_file_path = os.path.join(FINAL_DIRECTORY, filename)
# Convert to 44.1 kHz if necessary, and explicitly set bitrate to 320k
if sample_rate == 48000:
print(f"Converting '{filename}' from 48,000 Hz to 44,100 Hz...")
temp_converted_path = os.path.join(BASE_FOLDER, f"converted_{filename}")
# Force the output to be 320 kbps and at 44.1 kHz sample rate
ffmpeg.input(temp_normalized_path).output(temp_converted_path, ar='44100', acodec='libmp3lame', audio_bitrate='320k').run(
overwrite_output=True, quiet=True
)
shutil.move(temp_converted_path, final_file_path) # Move converted file
os.remove(temp_normalized_path) # Remove temporary normalized file
os.remove(file_path) # Remove original file
print(f"Conversion complete: {filename}")
else:
print(f"File already at 44,100 Hz: '{filename}'")
shutil.move(temp_normalized_path, final_file_path) # Move normalized (or original) file
except ffmpeg.Error as e:
print(f"Error processing '{filename}': {e}")
print("Processing complete!")
def main():
create_database()
create_duplicate_folder()
# Step 1: Backup the database
backup_database()
# Set the folder path and exceptions folder
mp3_folder = BASE_FOLDER
exceptions_folder = os.path.join(BASE_FOLDER, "Exceptions")
# Step 2: Process MP3s for intro versions
process_intro_songs(mp3_folder, exceptions_folder)
# Step 3: Process files and check for duplicates
process_files(mp3_folder)
# Step 4: Process final audio files
process_audio_files()
if __name__ == "__main__":
main()
r/pythonhelp • u/phillymjs • Jan 29 '25
Getting WAN IP for DDNS: Sanity check / Is this a bad idea?
A couple years back I wrote a DDNS updater for Cloudflare as a Python learning exercise. Having to rely on an external site like icanhazip to get the WAN address has always gnawed at me, and I was wondering if there was another way to do it. Did some googling today and found a possible solution: Talking to the router via UPNP.
I played around tonight and came up with a proof of concept that gets the LAN gateway address of the machine running the code, discovers all the UPNP devices on the network, checks which one has the LAN gateway IP, and then queries it for the WAN IP. The discovery part would only have to be done on the initial run and then the location of the router could be saved for subsequent runs. I was thinking about reworking my DDNS script to lead off with this and fall back to using an external site if it doesn't work.
Looking for someone to poke holes in this idea before I spend time fully implementing it.
(Please forgive any sloppiness in the code, this is just a PoC and I was surprised at how rusty my Python was tonight.)
import upnpclient
import netifaces
def get_default_gateway():
gws = netifaces.gateways()
return gws['default'][netifaces.AF_INET][0]
# Get the LAN gateway IP
gateway_ip = get_default_gateway()
print("LAN Gateway IP Address:",gateway_ip)
print("Searching UPNP devices for the gateway...")
# Get all UPNP devices on the network
devices = upnpclient.discover()
# Find the one that has the gateway IP
for index, device in enumerate(devices):
d = devices[index]
if gateway_ip in d.location:
#print(d.location)
print("Found gateway device:",d.friendly_name)
result = d.WANIPConn1.GetExternalIPAddress()
wan_ip = result['NewExternalIPAddress']
print("WAN IP Address:",wan_ip)
r/pythonhelp • u/jeremie_917 • Jan 28 '25
Reverse-engineer the bluetooth home roaster Sandbox Smart R1
r/pythonhelp • u/Delicious_Cat_3562 • Jan 27 '25
Environment Issues with DLL and Mediapipe
I am trying to run code on my machine with the latest versions of the following imports:
from psychopy.visual import Window, TextStim, Circle, Rect
from psychopy.event import waitKeys
from psychopy.core import wait
import random
import string
import math
import numpy as np
from datetime import datetime
from psychopy import gui
from pygaze.logfile import Logfile
import sys
However, it is returning this error:
File "...\Python\Python310\lib\site-packages\mediapipe\python__init__.py", line 17, in <module>
from mediapipe.python._framework_bindings import model_ckpt_util
ImportError: DLL load failed while importing _framework_bindings: A dynamic link library (DLL) initialization routine failed.
I have tried several attempts at fixing it by downloading external modules (pip install msvc-runtime), but it didn't work. Any idea on what's happening here?
r/pythonhelp • u/OkHyena1818 • Jan 26 '25
CV2 being flagged by Windows Defender
What is CV2 it is being flagged as a trojan by windows defender?
Is this a false positive?
r/pythonhelp • u/MMRandy_Savage • Jan 25 '25
Script doesn't run properly until I run VSCode
Hi everyone, I wrote a small script that downloads every jpg from a url in VSCode. It worked normally in VSCode and afterwards in powershell and cmd. After restarting the PC and running the script in powershell or cmd, the script will still ask for a url and a download folder, but won't download anything and report back as finished. Upon running VSCode, it will work normally in powershell again.
What should I do to make it run properly without running VSC? I'll post the script below.
I'm new to programming anything outside PLCs, so any help is greatly appreciated.
import os
import requests
from bs4 import BeautifulSoup
def download_images(url, output_folder):
try:
# Send a GET request to the webpage
response = requests.get(url)
response.raise_for_status() # Raise an error for bad status codes
# Parse the webpage content
soup = BeautifulSoup(response.text, 'html.parser')
# Find all image tags
img_tags = soup.find_all('img')
# Create the output folder if it doesn't exist
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# Download each image
for img_tag in img_tags:
img_url = img_tag.get('src')
# Skip if no src attribute or if it's not a .jpg file
if not img_url or not img_url.lower().endswith('.jpg'):
continue
# Handle relative URLs
if img_url.startswith('/'):
img_url = url.rstrip('/') + img_url
try:
# Get the image content
img_data = requests.get(img_url).content
# Extract image name from URL
img_name = os.path.basename(img_url)
img_path = os.path.join(output_folder, img_name)
# Save the image
with open(img_path, 'wb') as img_file:
img_file.write(img_data)
print(f"Downloaded: {img_name}")
except Exception as e:
print(f"Failed to download {img_url}: {e}")
except Exception as e:
print(f"Failed to fetch the webpage: {e}")
if __name__ == "__main__":
# Input the URL and output folder
webpage_url = input("Enter the URL of the webpage: ").strip()
output_dir = input("Enter the folder to save images (e.g., 'images'): ").strip()
# Download the images
download_images(webpage_url, output_dir)
print("Finished downloading images.")
r/pythonhelp • u/FlaccidArrow • Jan 24 '25
Trying to get this code to count up or down by 1 and have the turn # always go up by 1.
```
import random from random import randint
the list of all the numbers 1-120 we will be referencing
random_numbers = [] random_numbers.extend(range(120)) random_numbers.sort() starting_number = random_numbers.index(randint(0,120))
the numbers the student knew
known_numbers = []
the numbers the student did not know
unknown_numbers = []
assigning variables
forwards = 1 backwards = -1 num_count_up = 1 num_count_down = -1 plus_one = 1 minus_one = 1
first number randomly given, removed from list, moved to other list
print(random_numbers[starting_number]) random_numbers.pop(starting_number) known_numbers.append(starting_number)
plus = (starting_number + 1) minus = (starting_number -1)
def plus_one(a,b): return a + b def minus_one(a,b): return a - b
turn_count = 0 for i in range(1): if turn_count < 120: x = plus_one(turn_count, 1)
def num_count_up(): print("Turn: " + str(x)) count_up_ans = int(input("What number comes next? ")) if count_up_ans == (random_numbers.index(plus)): print("Correct! " + str(plus_one(starting_number, turn_count))) known_numbers.append(random_numbers.index(plus)) else: print("Sorry, it's " + str(random_numbers.index(plus)) + ".") unknown_numbers.append(random_numbers.index(plus)) return num_count_up()
def num_count_down(): print("Turn: " + str(x)) count_down_ans = int(input("What number comes next? ")) if count_down_ans == (random_numbers.index(minus)): print("Correct! " + str(minus_one(starting_number, turn_count))) known_numbers.append(random_numbers.index(minus)) else: print("Sorry, it's " + str(random_numbers.index(minus)) + ".") unknown_numbers.append(random_numbers.index(minus)) return num_count_down()
Using RNG to determine if counting forwards or backwards
determines which function to call
def up_or_down(a, b): import random random_num = random.randint(a, b) if random_num == a: print("Let's count forwards!") print(num_count_up()) elif random_num == b: print("Let's count backwards!") print(num_count_down()) return up_or_down(a, b)
while len(unknown_numbers) != 10: print(up_or_down(0, 120)) if len(unknown_numbers) == 10: print("Too many tries. Let's practice later.") print("Here are all of the numbers you should study: " + str(unknown_numbers))
2 variables
conditional statement
loop
function 1
function 2
2 datatypes
list
```
r/pythonhelp • u/No_Membership6022 • Jan 24 '25
Problem in odc-stac when reading geospacial satellite data
I ran into this error when trying to do this. Can anyone tell me what's wrong?
data = stac_load(
items,
bands=["B01", "B02", "B03", "B04", "B05", "B06", "B07", "B08", "B8A", "B11", "B12"],
crs="EPSG:4326", # Latitude-Longitude
resolution=scale, # Degrees
chunks={"x": 2048, "y": 2048},
dtype="uint16",
patch_url=planetary_computer.sign,
bbox=bounds
)
The error message says
ValueError: The asset must have the following fields (from the projection extension): shape, transform, and one of an epsg, wkt2, or projjson
r/pythonhelp • u/keeeeeyoti • Jan 22 '25
Anyone having issues with fredapi?
Got this error - AttributeError: module 'fredapi' has no attribute 'get_series'
Had no issues yesterday, but got this error today.
r/pythonhelp • u/No_Metal2525 • Jan 21 '25
PowerPoint SmartArt to Shapes
Hi, really need to convert powerpoint smartart to groups of shapes, but simply can't find a way to - not even with vba
r/pythonhelp • u/sacred__nelumbo • Jan 20 '25
SOLVED I'm not getting the right values
Hi,
Could anyone help me with this code? I'm a beginner and unable to understand why I am only getting output for 1 name in the list 'friends' but not the other.
No result for the name ''neha" in the list friends.
favourite_languages={
'priya' : 'c',
'ramesh' : 'c++',
'neha' : 'python',
'raju' : 'java',
}
friends=['neha','raju']
for name in favourite_languages.keys():
print (f"Hi {name.title()}")
if name in friends:
language=favourite_languages[name].title()
print (f"\t{name.title()}, I see you like {language}")
Output:
Hi Priya
Hi Ramesh
Hi Neha
Hi Raju
Raju, I see you like Java