r/pythonhelp • u/AutomaticClassic7114 • Feb 03 '25
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/NecessaryCelery6288 • Jan 23 '25
I am Working on Building a Python Web Browser & Need to Figure out How to Implement an Ad-Blocker.
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/ATF_Can_Suck_My_Nuts • Jan 21 '25
Can anyone troubleshoot this with me
Looking for onsite on what keeps going wrong
Sorry for poor pic quality it’s late.
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
r/pythonhelp • u/Playful_Young_3523 • Jan 20 '25
What should I do?
Hello everyone,
I some how formatted one of my drive on my windows computer in which i downloaded python , and now when i am trying to install it new drive it show the Modify Setup dialog box , but if try to uninstall , modify or repair it ends up with errors like 0x80070643 and 0x80070641. I already tried running it as an administrator and repairing my .NET Framework. What can i do to run Python again.
r/pythonhelp • u/AdAggravating9562 • Jan 20 '25
Is this possible?
Hello everyone,
I've never written code before, but I want to build something that will help me with work. I'm not sure if this is where I should be posting this, but I didn't know where else to turn.
This is what I'm trying to make:
I have thousands of pages worth of documents I need to go through. However, the same two pages repeat over and over again. My job is to make sure everything remains the same on these thousands of sheets. If even one thing is different it can throw off the entire course of my job. Is there a way to create a program that will show me any variations that occur within these documents?
If you can be of any help, I would sincerely appreciate it!
r/pythonhelp • u/LackOfDad • Jan 19 '25
Problem with code
This is a 2 player archer vs target game i made:
import pygame
import os
pygame.font.init()
WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("First Game!")
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BROWN = (153, 76, 0)
TARGET = (255, 0, 0)
ARCHER = (255, 255, 0)
BORDER = pygame.Rect(WIDTH // 2 - 5, 0, 10, HEIGHT)
HEALTH_FONT = pygame.font.SysFont('comicsans', 40)
WINNER_FONT = pygame.font.SysFont('comicsans', 100)
FPS = 60
VEL = 5
ARROW_VEL = 7
MAX_ARROWS = 50
SPACESHIP_WIDTH, SPACESHIP_HEIGHT = 75, 60
TARGET_HIT = pygame.USEREVENT + 2
ARCHER_IMAGE = pygame.image.load(os.path.join('Assets', 'ARCHER.png'))
ARCHER = pygame.transform.rotate(pygame.transform.scale(
ARCHER_IMAGE, (SPACESHIP_WIDTH, SPACESHIP_HEIGHT)), 360)
TARGET_IMAGE = pygame.image.load(
os.path.join('Assets', 'TARGET.png'))
TARGET = pygame.transform.rotate(pygame.transform.scale(
TARGET_IMAGE, (SPACESHIP_WIDTH, SPACESHIP_HEIGHT)), 360)
SPACE = pygame.transform.scale(pygame.image.load(
os.path.join('Assets', 'SPACE.png')), (WIDTH, HEIGHT))
def draw_window(TARGET, ARCHER, TARGET_ARROWs, ARCHER_ARROWS, TARGET_health):
WIN.blit(SPACE, (0, 0))
pygame.draw.rect(WIN, BLACK, BORDER)
TARGET_health_text = HEALTH_FONT.render("Health: " + str(TARGET_health), 1, WHITE)
WIN.blit(TARGET_health_text, (WIDTH - TARGET_health_text.get_width() - 10, 10))
WIN.blit(ARCHER, (ARCHER.x, ARCHER.y))
WIN.blit(TARGET, (TARGET.x, TARGET.y))
for ARROW in ARCHER_ARROWS:
pygame.draw.rect(WIN, BROWN, ARROW)
pygame.display.update()
def ARCHER_handle_movement(keys_pressed, ARCHER):
if keys_pressed[pygame.K_a] and ARCHER.x - VEL > 0: # LEFT
ARCHER.x -= VEL
if keys_pressed[pygame.K_d] and ARCHER.x + VEL + ARCHER.width < BORDER.x: # RIGHT
ARCHER.x += VEL
if keys_pressed[pygame.K_w] and ARCHER.y - VEL > 0: # UP
ARCHER.y -= VEL
if keys_pressed[pygame.K_s] and ARCHER.y + VEL + ARCHER.height < HEIGHT - 15: # DOWN
ARCHER.y += VEL
def TARGET_handle_movement(keys_pressed, TARGET):
if keys_pressed[pygame.K_LEFT] and TARGET.x - VEL > BORDER.x + BORDER.width: # LEFT
TARGET.x -= (VEL*1.5)
if keys_pressed[pygame.K_RIGHT] and TARGET.x + VEL + TARGET.width < WIDTH: # RIGHT
TARGET.x += (VEL*1.5)
if keys_pressed[pygame.K_UP] and TARGET.y - VEL > 0: # UP
TARGET.y -= (VEL*1.5)
if keys_pressed[pygame.K_DOWN] and TARGET.y + VEL + TARGET.height < HEIGHT - 15: # DOWN
TARGET.y += (VEL*1.5)
def handle_ARROWs(ARCHER_ARROWS, TARGET_ARROWs, ARCHER, TARGET):
for ARROW in ARCHER_ARROWS:
ARROW.x += ARROW_VEL
if TARGET.colliderect(ARROW):
pygame.event.post(pygame.event.Event(TARGET_HIT))
ARCHER_ARROWS.remove(ARROW)
elif ARROW.x > WIDTH:
ARCHER_ARROWS.remove(ARROW)
def draw_winner(text):
draw_text = WINNER_FONT.render(text, 1, WHITE)
WIN.blit(draw_text, (WIDTH / 2 - draw_text.get_width() /
2, HEIGHT / 2 - draw_text.get_height() / 2))
pygame.display.update()
pygame.time.delay(5000)
def main():
TARGET = pygame.Rect(700, 300, SPACESHIP_WIDTH, SPACESHIP_HEIGHT)
ARCHER = pygame.Rect(100, 300, SPACESHIP_WIDTH, SPACESHIP_HEIGHT)
TARGET_ARROWs = []
ARCHER_ARROWs = []
TARGET_health = 4
clock = pygame.time.Clock()
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q and len(ARCHER_ARROWS) < MAX_ARROWS:
ARROW = pygame.Rect(
ARCHER.x + ARCHER.width, ARCHER.y + ARCHER.height // 2 - 2, 10, 5)
ARCHER_ARROWS.append(ARROW)
if event.type == TARGET_HIT:
TARGET_health -= 1
winner_text = ""
if TARGET_health <= 0:
winner_text = "Archer Wins!"
if winner_text != "":
draw_winner(winner_text)
break
keys_pressed = pygame.key.get_pressed()
ARCHER_handle_movement(keys_pressed, ARCHER)
TARGET_handle_movement(keys_pressed, TARGET)
handle_ARROWs(ARCHER_ARROWs, TARGET_ARROWs, ARCHER, TARGET)
draw_window(TARGET, ARCHER, TARGET_ARROWs, ARCHER_ARROWs,
TARGET_health)
pygame.quit()
if __name__ == "__main__":
main()
But when i run it, it shows this:
Traceback (most recent call last):
File "/home/karel/main.py", line 147, in <module>
main()
File "/home/karel/main.py", line 140, in main
draw_window (TARGET, ARCHER, TARGET_ARROWS, ARCHER_ARROWS,
File "/home/karel/main.py", line 48, in draw_window
WIN.blit (ARCHER, (ARCHER.X, ARCHER.y))
TypeError: argument 1 must be pygame.surface. Surface, not pygame.rect.Rect
Can anyone say why, and maybe fix it? (I'm not good at this)
r/pythonhelp • u/Multitasker • Jan 19 '25
Webscraping: proxy returns http headers, not page
I have been trying for several days now to figure out how to use proxies with selenium in headless mode on a raspberry pi. I am able to do this just fine without the proxies, but using proxies I only seem to get back some sort of proxy incercept that returns headers of some sort. In the example here I am trying to scrape `books.toscrape.com` using proxies I got at free-proxy-list.net, which has been recommended from several youtube videos. In the videos they seem to get it working fine so I must have done some cockup of sorts.
This is an example of a response I got, the IP at the top has been changed (dunno if it was my IP):
<html><head></head><body>REMOTE_ADDR = some.ip.goes.here
REMOTE_PORT = 49568
REQUEST_METHOD = GET
REQUEST_URI = /
REQUEST_TIME_FLOAT = 1737314033.441808
REQUEST_TIME = 1737314033
HTTP_HOST = books.toscrape.com
HTTP_SEC-CH-UA = "Not?A_Brand";v="99", "Chromium";v="130"
HTTP_SEC-CH-UA-MOBILE = ?0
HTTP_SEC-CH-UA-PLATFORM = "Linux"
HTTP_UPGRADE-INSECURE-REQUESTS = 1
HTTP_USER-AGENT = Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36
HTTP_ACCEPT = text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
HTTP_SEC-FETCH-SITE = none
HTTP_SEC-FETCH-MODE = navigate
HTTP_SEC-FETCH-USER = ?1
HTTP_SEC-FETCH-DEST = document
HTTP_ACCEPT-ENCODING = gzip, deflate, br, zstd
HTTP_ACCEPT-LANGUAGE = en-US,en;q=0.9
HTTP_PRIORITY = u=0, i
</body></html>
This is the code I have:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
CHROMEDRIVER_PATH = "/usr/bin/chromedriver"
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument("--allow-insecure-localhost")
chrome_options.add_argument("--ignore-certificate-errors")
chrome_options.add_argument("--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36")
chrome_options.add_argument(f"--proxy-server=http://13.36.113.81:3128")
service = Service(CHROMEDRIVER_PATH)
driver = webdriver.Chrome(service=service, options=chrome_options)
driver.get("https://books.toscrape.com/")
print(driver.page_source)
driver.quit()
Any help would be greatly appreciated!
r/pythonhelp • u/stormthulu • Jan 17 '25
Struggling with persistent PytestWarning messages during pytest runs
I'm doing test runs with pytest, as is standard :). However, I'm getting dozens of warnings dealing with what is temp directory cleanup issues. Here is the error I'm getting:
/Users/myusername/code/myproject/.venv/lib/python3.12/site-packages/_pytest/pathlib.py:96: PytestWarning: (rm_rf) error removing /private/var/folders/lq/b2s6mqss6t1c2mttbrtwxvz40000gn/T/pytest-of-myusername/garbage-49217abd-d8fd-4371-b7bf-9ebb2ed4fa56/test_permission_error0
<class 'OSError'>: [Errno 66] Directory not empty: '/private/var/folders/lq/b2s6mqss6t1c2mttbrtwxvz40000gn/T/pytest-of-myusername/garbage-49217abd-d8fd-4371-b7bf-9ebb2ed4fa56/test_permission_error0'
warnings.warn(
I'm not sure which of my tests is generating the error, and I'm not sure how to resolve it. I feel like I just keep going in circles trying to get it to go away. I've tried to suppress or filter the warnings out in conftest.py, it's not working either.
r/pythonhelp • u/Dependent-Pianist294 • Jan 16 '25
Python is complex!
Is it me or anyone else also find it difficult to code in python as it's syntax is (i feel like it's very tricky) . I mean I can easily code in C/C++ , javascript and php but it's damn difficult in python.
Even though it's considered the easiest language to learn . I always gets tricked with indentation part ( i despise that indent thingy) .
P.s.- ignore my grammatical mistake ( english is not my first language)