r/pythonhelp • • Jun 02 '21

Using selenium for the first time and I cant get past this error

2 Upvotes

Code:

from selenium import webdriver
PATH ="C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get("reddit.com")

Error:

Traceback (most recent call last):
  File "file location", line 7, in <module>
    driver.get("reddit.com")
  File "C:\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 333, in get
    self.execute(Command.GET, {'url': url})
  File "C:\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Python39\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidArgumentException: Message: invalid argument
  (Session info: chrome=91.0.4472.77)

i think it may be because my version of chrome is newer than the driver, I dont know where to get older versions as google doesnt offer them and I dont trust third party websites


r/pythonhelp • • May 04 '21

HOMEWORK Help needed with functions and the random module

2 Upvotes
import random
import math

def calculate_number(n):         
   outputs=[]
   for j in range(2):
    x = random.random()           
    y = random.random()           
    print("(",x,",", y,")")       
    inputs=[x,y]
    for i in inputs:
     math.sqrt(x**2+y**2)
     output=calculate_number(inputs)
     return output

Hiya, I'm trying to make a function that generates two random numbers between 0 and 1, and then finds their distance from the origin point (after they are plotted)

I assume there are multiple issues with this code, but the one stopping me at the moment is it generates a ton of random numbers, when I only need two.

Any ideas? Cheers


r/pythonhelp • • Apr 25 '21

Tool code ArcPy

2 Upvotes

Hello I am coding a tool that is supposed to update a csv file and then diplay its x Y coordinates. I am currently just trying to get the insert row cursor part to work. this is what my code looks like so far and I keep getting the error

(Traceback (most recent call last):

File "C:/GISc450/BD_Proj/TESTADD.py", line 34, in <module>

main()

File "C:/GISc450/BD_Proj/TESTADD.py", line 29, in main

cursor.insertRow(row_vals)

TypeError: sequence size must match size of the row)

Not sure why this is, do you think it is my code or the table istelf?


r/pythonhelp • • Mar 30 '21

HOMEWORK Need to convert decimals into integers that are separated by commas

2 Upvotes

I have been stuck on a homework assignment where we need to read a dataset into python code supplied by my teacher. problem is, his code does not like decimals and refuses to give proper data without integers. Having virtually no experience with python, I had to probe him in order to get this code:

f=open("input.txt",).readlines()

fout=open("output.txt","w")

for line in f:

l = line.split(",")

for item in l:

	number = float(item)

	new_line = str(int(number)) + ","
fout.write(new_line)

fout.close()

Problem is, this code seems to only read the values at the end of each line (which are whole numbers) and writes only those to the output file. Further, the formatting is wrong, since they are in rows but just one long line. suffice to say I am terribly confused, and would appreciate any and all help. For reference, here is a sample of the file:

3.6216,8.6661,-2.8073,-0.44699,1

4.5459,8.1674,-2.4586,-1.4621,1

3.866,-2.6383,1.9242,0.10645,1

3.4566,9.5228,-4.0112,-3.5944,1

0.32924,-4.4552,4.5718,-0.9888,1

4.3684,9.6718,-3.9606,-3.1625,1

3.5912,3.0129,0.72888,0.56421,1

2.0922,-6.81,8.4636,-0.60216,1

3.2032,5.7588,-0.75345,-0.61251,1

1.5356,9.1772,-2.2718,-0.73535,1

and this is the output I get:

1,1,1,1,1,1,1,1,1,1,


r/pythonhelp • • Mar 23 '21

Can anyone explain what it means by Time complexity of this code? Homework question

2 Upvotes

r/pythonhelp • • Mar 16 '21

HOMEWORK Celsius to Fahrenheit Table Problem

2 Upvotes

The problem is: Write a program that displays a table of the Celsius temperatures 0 through 20 and the Fahrenheit equivalents. Use a loop to display the table.

The instructor wants the program to ask the user to input the beginning and ending Celsius temperatures instead of using 0 to 20. Is should also be created with a nested loop with the outer loop stopping the program when 0 is inputted for beginning and end temps and the inner loop calculates and prints the result.

So far I have this:

celsius = 0.0

fahrenheit = 0.0

user_celsius_beg = 0.0

user_celsius_end = 0.0

user_celsius_beg = int(input('Enter a beginning Celsius temperature: '))

user_celsius_end = int(input('\nEnter an ending Celsius tempeperature: '))

print("\nCelsius Temperature\tFahrenheit Temperature")

print('-----------------------------------------------')

for celsius in range(user_celsius_beg, user_celsius_end + 1):

fahrenheit = ((9 / 5) * celsius) + 32

print("\t", celsius, "\t\t\t", format(fahrenheit, ".2f"))

I had an idea of using this but when I do it keeps repeating the same values over and over in the table. I know why it keeps repeating the values but I do not know how to only have it display once. So my question is, is there a way to create this with a nested loop? :

while not(user_celsius_beg == 0 and user_celsius_end == 0):

for celsius in range(user_celsius_beg, user_celsius_end + 1):

fahrenheit = ((9 / 5) * celsius) + 32

print("\t", celsius, "\t\t\t", format(fahrenheit, ".2f"))


r/pythonhelp • • Feb 23 '21

How do I structure my internal modules with multiple references?

2 Upvotes

I have a commonly used datetime chunk of code that just handles the current ISO datestamp in the country which I live in.

timestamp_now_iso_sgt = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=8))).isoformat()

Inside my custom logging module, I am referencing the current time stamp in a function. Inside my main application code, it is also referencing the current time stamp.

What should I do?

  1. split off the timestamp code into its own module, and import it in the logging module and main app code?

  2. split off the timestamp code and handle it in the the main app code when the custom logging functions are called? Eg. CustomLogging(loginput, mod_timestamp.now)

  3. embed the timestamp code separately inside the module and main app code?


r/pythonhelp • • Feb 21 '21

Python Watermarking - Prevent image size and quality reduction

2 Upvotes

I have this script which is successfully applying a watermark to an image, resizing the watermark and setting the image "quality". I find that it's actually reducing the quality and resizing it to be smaller than I want.

This is a telegram bot that I'm using, I send the image to the bot, the bot is adding the watermark and then resizing. I don't want the resizing part at all. I want the original size + the watermark.

QUESTION: How do i change this so it doesn't resize my original image that the watermark is added to?

CURRENT FLOW

  1. I sent image to my bot which activates the script

  2. The script adds a watermark and resizes the image

  3. The script sends the resized image back to me with the watermark included

DESIRED FLOW

  1. I send image to my bot which activates script

  2. The script adds a watermark but does not resize the original image

  3. The script sends the image back to me with the watermark included

CODE 1

# -*- coding: utf-8 -*-
import telebot
import config
import random
import os
import time
from tools.tools import getting_ready

bot = telebot.TeleBot(config.BOT_TOKEN)


@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
    bot.send_message(message.chat.id, 'Hi, Send or Forward me a PHOTO!')


@bot.message_handler(func=lambda message: True)
def echo_all(message):
    bot.reply_to(message, 'Send /start or /help')


@bot.message_handler(content_types=["photo"])
def send_watermark(message):
    chat_id = message.chat.id
    sent_message = bot.reply_to(message, 'Downloading...')
    message_id = sent_message.message_id
    file = bot.get_file(message.photo[0].file_id)
    downloaded_file = bot.download_file(file.file_path)
    bot.edit_message_text(f'Downloaded!\n\nNow, Genarating Watermarks...\n\ncurrent watermark: {config.WATERMARK}', chat_id=chat_id, message_id=message_id)
    __path = 'images/' + str(random.randint(100000, 999999)) + '.tmp'
    with open(__path, 'wb') as f:
        f.write(downloaded_file)
    fname = getting_ready(__path)
    os.remove(__path)
    time.sleep(2)
    bot.edit_message_text('Now, Uploading...', chat_id=chat_id, message_id=message_id)
    for i in ('black','white',):
        __file = 'images/out/{}/{}'.format(i, fname)
        __photo = open(__file, 'rb')
        bot.send_photo(message.chat.id, __photo, reply_to_message_id=message.message_id)
        os.remove(__file)
    bot.delete_message(chat_id=chat_id, message_id=message_id)


print('watermark bot started successfully!')
bot.polling()

CODE 2

from PIL import Image, ImageFont, ImageDraw, ImageEnhance
import hashlib
import piexif
import config


def getting_ready(path):
    fname = md5(path) + '.jpg'
    image = Image.open(path).convert('RGB')
    try:
        exif_dict = piexif.load(image.info['exif'])
        orientation = exif_dict['0th'][274]
    except KeyError:
        orientation = None
    rotate_values = {3: 180, 6: 270, 8: 90}
    if orientation in rotate_values:
        image = image.rotate(rotate_values[orientation], expand=True)
    for color in ['black', 'white']:
        watermark(image, fname, color)
    return fname


def watermark(img, new_fname, color):
    text = config.WATERMARK
    wm = Image.new('RGBA', img.size, (0, 0, 0, 0))
    fontsize = img.size[1] // 100 * config.FONT_SIZE
    font = ImageFont.truetype(f'tools/fonts/{config.FONT_NAME}', fontsize)
    indent = fontsize // 8
    w, h = font.getsize(text)
    text_position = (img.size[0] - w - indent, img.size[1] - h - indent)
    draw = ImageDraw.Draw(wm, 'RGBA')
    draw.text(text_position, text, font=font, fill=color)
    alpha = wm.split()[3]
    alpha = ImageEnhance.Brightness(alpha).enhance(config.TRANSPARENCY)
    wm.putalpha(alpha)
    out_path = 'images/out/{}/{}'.format(color, new_fname)
    Image.composite(wm, img, wm).save(out_path, 'JPEG', optimize=False, quality=config.QUALITY)


def md5(path):
    with open(path, 'rb') as f:
        md5hash = hashlib.md5()
        for chunk in iter(lambda: f.read(4096), b''):
            md5hash.update(chunk)
    return md5hash.hexdigest()

r/pythonhelp • • Feb 15 '21

Cannot figure out invalid syntax error.

2 Upvotes

Im currently making a discord bot that pulls data from yahoo_fin api and posts the data in the channel. I cannot figure out why the code is giving me an error on line 23, start = 0. Can someone help me?


r/pythonhelp • • Feb 02 '21

HOMEWORK Need guidance in using python classes.

2 Upvotes

Hello,

before I begin I just wanted to say that I am brand new to any type of programming So thank you in advance for your patience and help.

I am currently working on a school assignment utilizing python classes to:

1.) Create a Vehicle class with the following attributes and functions:

Attributes: make, model, color, fuelType, options (which will be defined as a python list chosen by the user when presented with a menu of programmer chosen vehicle options that can apply to both cars and pickup trucks

Options: power mirrors, power locks, power windows, remote start, backup camera, bluetooth, cruise control, GPS

functions: getMake(), getModel(), getColor(), getFuelType(), getOptions().

2.) Create a Car class as a child of the Vehicle class with the following attributes and functions:

Attributes: engineSize, numDoors

Functions: getEngineSize(), getNumdoors()

3.) Create a Pickup class as a child of the Vehicle class with the attributes and functions :

Attributes: cabStyle, bedLength

Functions: getCabstyle(), getBedLength()

4.) Your program will prompt the user to create at least one object of each type (Carand Pickup) allowing the user to define the attributes of the vehicles in their garage.

5.) Using a menu system and capturing user input your program will allow the user the choice of adding a car or pickup truck and define the vehicle's attributes. 

6.)

The user will choose from a list of options to add to the vehicle's options list and must choose a minimum of one vehicle option per vehicle. 

7.) Your program must allow the user to have multiple vehicles in their virtual garage and must have at least one Car and one Pickup.

8.) When the user is finished adding vehicles to their virtual garage the program will output the vehicles in their garage and their attributes.

whew, what a list! Alas, I am lost in the woods on this one as I'm not quite sure where to begin with the user inputs, and I don't really know what the requirements are asking for within the functions. All I have done so far is code the classes (See screenshot) should I begin with creating a class method for the inputs?

Again I appreciate any advice on how I should move forward with the rest of the requirements.


r/pythonhelp • • Jan 21 '21

Python+apache, what exactly am i doing wrong, i want HTML to communicate with py and execute the py file and show result?

Post image
2 Upvotes

r/pythonhelp • • Jan 10 '21

Help! What am I doing wrong?

Post image
2 Upvotes

r/pythonhelp • • Dec 10 '20

SOLVED Help with a basic Monty Hall program

2 Upvotes

I need to write a simple code for a Monty hall program for my Python class, however I cannot wrap my head around how the selection algorithm needs to work.

Here is an example of the one of the outputs I need to display:

Which door would you like to pick: 1

There is a goat behind door #2.

Would you like to change you pick? No

The car was behind door #3

You lost.


r/pythonhelp • • Dec 03 '20

Python Syntax Errors

2 Upvotes

Hi!

I was practicing some pretty easy scripts and all it does is see what a number is and print 'big' or 'small'. so can anyone tell me what the problem is?

x = 5

if x = 5 :

print('big')

if x = 1 :

print('small')

print('done!')

Also im using Pyscripter as an IDE


r/pythonhelp • • Nov 10 '20

Keyboard.is_pressed() While Loop Condition

2 Upvotes

I'm writing a bot that plays the game on aimbooster.com. It takes a screenshot of the game and then clicks where it sees the bullseye. This runs in a while loop so that it can keep taking screenshots. To stop the while loop, the user should press the 'q' key on their keyboard. So I have the while loop set as such:

while not keyboard.is_pressed('q'):
    # Loop body

 

This works fine sometimes, but if the game speeds up and there are more mouse clicks, then I have to keep spamming 'q' and hope it goes through. Any ideas on how to avoid this issue? Thanks!


r/pythonhelp • • Nov 03 '20

My LEDs wont change when they are supposed to.

2 Upvotes
import json
import requests
from time import sleep
import os
import subprocess
from gpiozero import LED


green = LED(18)
red = LED(23)

while True:
    jsonFile = open('/home/pi/pithings/token.json', 'r')
    values = json.load(jsonFile)
    jsonFile.close()
    token = values["access_token"]
    # print(token)
    url = "https://us.api.blizzard.com/data/wow/connected-realm/11?namespace=dynamic-us&locale=en_US&access_token={0}".format(
        token)
    # print(url)
    # print(token)
    response = requests.get(url)
    realmstat = "False"


    def jprint(obj):
        text = json.dumps(obj, sort_keys=True, indent=4)
        print(text)


    status = response.json()['status']

    status_2 = (status['name'])

    if status_2 == 'Up':
        green.on()
        print('Up')
    elif status_2 == 'Down':
        red.on()
        print('Down')
    else:
        green.on()
        red.on()
    sleep(10)

I have a raspberry pi Zero W set up with 2 LEDs to show the status of my WoW Realm (thanks to redditors here for helping get that part working a while back), but when the status changes, the LEDs stay the same. If I restart the script, the correct color will light. what am i getting wrong?


r/pythonhelp • • Oct 28 '20

I need help decipher a shuffle cipher

2 Upvotes

I am having an issue making a function that decrypts the encrypting function


r/pythonhelp • • Oct 26 '20

Python Parsing help

2 Upvotes

Hey all,
I am very new to python and basically have a project with text files. I want to store the first word in a line, and then search for that word in another file. Then, once I find the line that contains that word, I want to print specific words from the line (which is separated by whitespaces) into another file.

For example, the first word in my first line of my first file is "bird". I then search for the line that contains "bird" in my second file (assuming only one does) and I get the words that are between the 4th and 5th space in that line and print it in another file.

I do know the basic of stripping line and reading/writing files, but I do not know how to basically make the for loop part of get the word between specific spaces. Anything helps, sorry I am a noob.

Thank you in advance!


r/pythonhelp • • Sep 27 '20

Python Help (Karel)

2 Upvotes

I am working on a project for a class that has a predefined set of functions. You are still able to define your own functions. The objective is that Karel needs to follow the path to get back home. This has to work in multiple worlds. I have been semi successful in that I was able to get it to work in the first world. I have been unable to get it to word in the second world and the third world despite having been trying for the past six days. I have used breakpoint() in my code as a placeholder for when I get to that part of the problem.

Here is my code:

World 1:

World: 2

World 3:


r/pythonhelp • • Aug 26 '20

Build RCS chatbot

2 Upvotes

I've been asked to create a super dummy RCS chatbot with Oranges API. I'm not a developer which makes it really hard for me.

I found a simple node.js template (also found in python) for an RCS chatbot that simply returns what the user says. I was hoping I could get some direction as to what I need to change other than the token,api_url, and bot_id which I highlighted in red.

At the end I'm expected to fill in this excel spreadshit. This is the list of the API and here it is expanded.

Has anyone did something similar? May I ask for some directions on what to change next? Huge thanks ahead.


r/pythonhelp • • Jul 25 '20

SOLVED Someone is better than the tutorial givers. But I can't figure him out. could someone help me understand his use of %?

2 Upvotes

https://www.practicepython.org/solution/2014/04/02/08-rock-paper-scissors-solutions.html

In this solution to an exercise there is a commentor who posted a way of doing it that I think is the best, but I cannot understand how he did some of it. Another commentor tried to explain it but it did not help me understand. I modified it to make it a function so that the game can repeat (indentures are messed up when pasted on here:

here is a screenshot of the code:

https://i.imgur.com/xf2SUe5.jpg

def thegame():
p_1 = input("\nchoose\n\n").lower()
p_2 = input('\nnow you choose\n\n').lower()

choices = list(['paper', 'rock', 'scissors'])
if p_1 not in choices:
print('\nnope, play again')
thegame()
if p_2 not in choices:
print('\nnopes, play again')
thegame()
if p_1 == p_2:
print('\ndraw')
if choices.index(p_1) == (choices.index(p_2) + 1) % 3:
print('\nplayer 2 wins!!!')
thegame()
if choices.index(p_2) == (choices.index(p_1) + 1) % 3:
print('\nplayer 1 wins!!!')
thegame()
thegame()

The trouble I have understanding is:

if choices.index(p_1) == (choices.index(p_2) + 1) % 3

Can someone please help explain how this works exactly?

ty


r/pythonhelp • • Jul 06 '20

Create Python PATH

2 Upvotes

Hi - I'm trying to do pip installs, but I get errors saying "is not a recognized as an internal or external command", so I tried following the guide below, but after creating the PATH and typing "Python" in the CMD, I still get "Python is not recognized as an internal or external command, operable program or batch file.

https://projects.raspberrypi.org/en/projects/using-pip-on-windows/4

I installed python from https://www.python.org/downloads/

Also, I'm not sure if this has an effect or not, but I do already have Anaconda installed on my computer, but I need to use PyCharm, which is why I'm trying to "reinstall" Python.


r/pythonhelp • • Jun 10 '20

Need help with this python code not sure whats wrong with line 229

Post image
2 Upvotes

r/pythonhelp • • Jun 02 '20

Is NumPy a library?

2 Upvotes

reference

hey there!

In the reference, "Use Python generator to produce a range of float numbers without using any library or module" is listed under "Goals of article".

Then, later in the article it states "NumPy library has various numeric functions and mathematical functions to operate on multi-dimensional arrays and matrices.". Doesn't NumPy count as a library? Is this article ill written or am I missing something?