I'm new-ish to Python and I'm having trouble achieving a result that I want. I'm opening a text file called urldata.txt which contains URLs that I need to break down by scheme, server, and path.
I have retrieved the data from the file:
urls = open("urldata.txt").read()
print(urls)
this returns:
http://www.google.com
https://twitter.com/search?q=%23ASUcis355
https://github.com/asu-cis-355/course-info
I want to break these URLs into 3 pieces each so that when I enter
urls.scheme()
urls.server()
urls.path()
It will return me the scheme of each URL when I enter
urls.scheme()
'http','https','https'
Then it will return the server when I enter
urls.server()
'google.com'
'twitter.com'
'github.com'
Finally, it will return the path when I enter
urls.path()
'/'
'/search?q=%23ASUcis355'
'/asu-cis-355/course-info'
I have defined a class to do this; however, I receive an error saying 'scheme() missing 1 required positional argument: 'self' Below is my class and the def parts to it that I have created.
class urls:
def __init__(self,url):
self.urls=urls
def scheme(self):
return urls.split("://")[0]
def server(self):
return urls.split("/")[2]
def path(self):
return urls.split(".com/")[1]
Any help at all is greatly appreciated!
This exists already. It's called urlparse:
from urllib.parse import urlparse
d = urlparse('https://twitter.com/search?q=%23ASUcis355')
print(d)
Output:
ParseResult(scheme='https', netloc='twitter.com', path='/search', params='', query='q=%23ASUcis355', fragment='')
If you attempt to call a class definition (what urls' is) without creating an instance of this class in Python3 then you get this error
>>> urls.scheme()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: scheme() missing 1 required positional argument: 'self'
>>>
But if you create an instance of urls and then use that instance this works as intended
>>> url_instance = urls("http://www.google.com")
>>> url_instance.scheme()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in scheme
AttributeError: type object 'urls' has no attribute 'split'
Note that this fixes your current error but your code isn't correct as is. I'll leave you to figure out what's happening with this error.
The difference between a class definition (or type) and an instance of the class has some interesting nuance but generally speaking
class Thing:
pass
is a class definition and
thing_instance = Thing()
Is an instance of the class.
Related
I'm going crazy trying to perform simple editing while creating a Python class constructor. I can create the simple class and constructor variable but once I try to change the names of the variable I get a KeyError.
The class is below:
class Collect:
def __init__(self, **kwargs):
self.foo = kwargs["foo"]
And the script where I instantiate the class and print out its attributes is below:
import mapper as m
payload = m.Collect(foo="Hello")
print(payload.foo)
Now this works just fine, but if I change "foo" to "bar" I get a KeyError Like below:
class Collect:
def __init__(self, **kwargs):
self.bar = kwargs["bar"]
and then running:
import mapper as m
payload = m.Collect(bar="Hello")
print(payload.bar)
will throw the following error:
Traceback (most recent call last): File "<stdin>", line 1, in
<module> File
"/path/to/mapper.py",
line 8, in __init__
self.bar = kwargs["bar"] KeyError: 'foo'
And the print function will throw the error below:
Traceback (most recent call last): File "<stdin>", line 1, in
<module> AttributeError: 'Collect' object has no attribute 'bar'
The weird thing is that if I hit save and then close VSCode and reopen, the new class with bar will work just fine. And, also even if I don't close VSCode the class will instantiate and the print statement will run just fine when I switch to Debug mode and run it. But when I try to highlight it and run a selection it throws that error.
How can I just test if the code works using the run selection operations and not relying on running in debug mode with breakpoints or having to close and reopen VSCode?
The solution was to reload my Python session. The VSCode reload extension makes this easy.
I'm trying to create a Python program that is able to open a youtube video, and then skip the ad in it. Here is what I have:
class MusicPlayer():
def __init__(self):
self.driver = webdriver.Safari()
self.driver.get("https://www.youtube.com/watch?v=suia_i5dEZc")
sleep(7)
skipAd = self.driver.find_element_by_class_name('ytp-ad-skip-button-container')
def skipAdFunction(self):
threading.Timer(3,skipAdFunction).start()
if(skipAd.is_enabled() or skipAd.is_displayed()):
skipAd.click()
skipAdFunction()
However, I'm not sure why this is happening, but I keep getting this error:
Traceback (most recent call last):
File "aivoices.py", line 52, in <module>
MusicPlayer()
File "aivoices.py", line 17, in __init__
skipAdFunction()
TypeError: skipAdFunction() missing 1 required positional argument: 'self'
It has something to do with self, but I'm sure if I'm supposed to have it or not. Can someone also explain me whether I need it in this occasion or not?
You should instead write self.skipAdFunction() when you call the function.
Alternatively, you can define skipAdFunction outside of the class and you won't have to mention self anywhere.
Edit:
As per Charles' comment, this is incorrect, my apologies. When you have a nested function defined within a class method, python does not expect/require you to have the positional argument self. Therefore, you can fix it like so:
class MusicPlayer():
def __init__(self):
# stuff you had here
def skipAdFunction():
threading.Timer(3,skipAdFunction).start()
if(skipAd.is_enabled() or skipAd.is_displayed()):
skipAd.click()
skipAdFunction()
I want to get a class reference from class object in Python. Normally I use class name as a valid reference, but it does not always work.
Consider this code:
import inspect
import unittest
import pywin32_testutil
mro=inspect.getmro(pywin32_testutil.TestProgram)
mro[0]
> <class 'pywin32_testutil.TestProgram'>
mro[0].__module__ + '.' + mro[0].__name__
>'pywin32_testutil.TestProgram'
pywin32_testutil.TestProgram
> <class 'pywin32_testutil.TestProgram'>
From the object I'm able to determine class name and using class name I can get class object. However it does not always work. Continuing the example:
mro[1]
> <class 'unittest.main.TestProgram'>
mro[1].__module__ + '.' + mro[1].__name__
> 'unittest.main.TestProgram'
so far so good, however unittest.main.TestProgram reference is invalid:
unittest.main.TestProgram
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'TestProgram' has no attribute 'TestProgram'
How can I work around that?
I am playing with pyelliptic, but I can't use the method raw_get_ecdh_key defined in the file ecc.py.
Here's my example code:
>>> import pyelliptic
>>> pubkey1="0453eb8248f42b00d057bc1adc724c4c841ec75851d6cd86f56f9bae5223219c7d3c7aff832d2383dfec167327ef38e9bf066690a8f94c055b336a607cebc2dddf".decode('hex')
>>> pubkey2="04678b95e902b04817ba258ecd3dbb2150d83850848a3b8523c11d51b6a9f89b93ea82db74ba82ba44fadb050b35eae8b96f3738e88c7c117227303a528c8df985".decode('hex')
>>> pyelliptic.ECC.raw_get_ecdh_key(pubkey1, pubkey2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method raw_get_ecdh_key() must be called with ECC instance as first argument (got str instance instead)
I searched and found many questions on the subject here. I learned that I need to call ECC() instead of ECC, but it doesn't work any better:
>>> pyelliptic.ECC().raw_get_ecdh_key(pubkey1, pubkey2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/pyelliptic/ecc.py", line 324, in raw_get_ecdh_key
OpenSSL.EC_KEY_free(own_key)
UnboundLocalError: local variable 'own_key' referenced before assignment
I can't figure what's wrong. I checked and the variable own_key should be referenced.
It's a very obvious bug in pyelliptic - if you look at the code, the part where own_key is defined (ecc.py line 301) is wrapped in huge try/finally block. If an exception is raised (and not managed) before line 301 (which is obviously what happened to you), then the execution flow jumps to the finally block, which to tries to reference own_key which at this point has not yet been defined.
You can fix by cloning the git repo and editing the raw_get_ecdh_key function's code so 1. the relevant local variables are defined at the beginning of the function before the try block (setting them to None) and 2. in the finally block these variables are tested against None before trying to use them to free resources, ie (untested):
def raw_get_ecdh_key(self, pubkey_x, pubkey_y):
other_key = None
other_pub_key_x = None
other_pub_key_y = None
other_pub_key = None
own_key = None
own_priv_key = None
try:
# (snip code)
finally:
if other_key is not None:
OpenSSL.EC_KEY_free(other_key)
if other_pub_key_x is not None:
OpenSSL.BN_free(other_pub_key_x)
if other_pub_key_y is not None:
OpenSSL.BN_free(other_pub_key_y)
if other_pub_key is not None:
OpenSSL.EC_POINT_free(other_pub_key)
if own_key is not None:
OpenSSL.EC_KEY_free(own_key)
if own_priv_key is not None:
OpenSSL.BN_free(own_priv_key)
And then run the the unittests (eventually adding some tests for this case) and submit a pull request to the author.
Note that you'll have applied this (untested) fix you should have another error - the one that sent you in the finally block at first - but at least you should then have more infos about why the call failed.
I try to create a class instance of BaseHTTPRequestHandler but I have an error message.
Here is what I did :
>>> from BaseHTTPServer import BaseHTTPRequestHandler
>>> obj=BaseHTTPRequestHandler()
>>> obj.send_response(200)
I got :
>>> obj=BaseHTTPRequestHandler()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() takes exactly 4 arguments (1 given)
Could you please give me some advice
The signature of BaseHTTPRequestHandler is as follows
class BaseHTTPServer.BaseHTTPRequestHandler(request, client_address, server)
The problem is that youre not providing the values it needs
You can check https://docs.python.org/2/library/basehttpserver.html#module-BaseHTTPServer for detailed info on what it requires exactly.
As #iCodez commented, self counts as 1 of the 4 needed arguments, but is passed implicitly, so you just need to pass the other 3