python BaseHTTPRequestHandler instance error - python

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

Related

Calling function causes TypeError: missing 1 required positional argument: 'self'

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()

Splitting Lines in Python in a List?

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.

Does python consider any method without cls or self arguments implicitly as static?

The following are test classes with methods not taking in cls or self arguments and dont have #staticmethod decorator. They work like normal static methods without complaining about arguments. This seems contrary to my understanding of python methods. Does python automatically treat non-class, non-instance methods as static?
>>> class Test():
... def testme(s):
... print(s)
...
>>> Test.testme('hello')
hello
>>> class Test():
... def testme():
... print('no')
...
>>> Test.testme()
no
P.S: I am using python3.4
It sort of does, yes. However, note that if you call such an "implicit static method" on an instance, you will get an error:
>>> Test().testme()
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
Test().testme()
TypeError: testme() takes 0 positional arguments but 1 was given
This is because the self parameter still gets passed, which doesn't happen with a proper #staticmethod:
>>> class Test:
#staticmethod
def testme():
print('no')
>>> Test.testme()
no
>>> Test().testme()
no
Note that this doesn't work in Python 2:
>>> class Test(object):
... def testme():
... print 'no'
...
>>> Test.testme()
Traceback (most recent call last):
File "<ipython-input-74-09d78063da08>", line 1, in <module>
Test.testme()
TypeError: unbound method testme() must be called with Test instance as first argument (got nothing instead)
But in Python 3, unbound methods were removed, as Alex Martelli points out in this answer. So really all you're doing is calling a plain function that happens to be defined inside the Test class.

Confusing TypeError exception error message caused by wrong number of method arguments in python

Let’s code for example a class called Rocket:
class Rocket():
def __init__(self, name):
print("Created a Rocket called '" + str(name) + "'!")
def liftOff(self):
print("10, 9 ,8 ,7 ... Lift Off!!")
and create an instance SaturnV of this class, but pass no arguments to the __init__ method:
SaturnV = Rocket()
We produce a TypeError:
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
SaturnV = Rocket()
TypeError: __init__() takes exactly 2 arguments (1 given)
Why does the compiler print, that __init__() takes exactly 2 arguments instead of 1 required name argument?
Why do they not change the error message to something like...
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
SaturnV = Rocket()
TypeError: __init__() takes exactly 1 argument in addition to the instance reference (0
arguments given)
Python counts the self keyword as an argument as well. That just means that it expects to be called on an class instance via the famous . (as in satrurnV.name)or you could optionally do a getattr(saturnV, "name") to retrieve the same thing.
The __init__() method is special because it gets called implicitly when you do Rocket() which is basically Rocket.__init__(). Now you see that the other argument, the one that you're missing is the name.
you also have an error in your code:
print("Created a Rocket called" + "'str(name)'" + "!")
should be
print("Created a Rocket called" + str(name) + "!")
str() function takes the object in the () and returns a string so there's no need to ut that under " "

How to use python-magic 5.19-1

I need to determine MIME-types from files without suffix in python3 and I thought of python-magic as a fitting solution therefor.
Unfortunately it does not work as described here:
https://github.com/ahupp/python-magic/blob/master/README.md
What happens is this:
>>> import magic
>>> magic.from_file("testdata/test.pdf")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'from_file'
So I had a look at the object, which provides me with the class Magic for which I found documentation here:
http://filemagic.readthedocs.org/en/latest/guide.html
I was surprised, that this did not work either:
>>> with magic.Magic() as m:
... pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() missing 1 required positional argument: 'ms'
>>> m = magic.Magic()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() missing 1 required positional argument: 'ms'
>>>
I could not find any information about how to use the class Magic anywhere, so I went on doing trial and error, until I figured out, that it accepts instances of LP_magic_set only for ms.
Some of them are returned by the module's methods
magic.magic_set() and magic_t().
So I tried to instanciate Magic with either of them.
When I then call the file() method from the instance, it will always return an empty result and the errlvl() method tells me error no. 22.
So how do I use magic anyway?
I think that you are confusing different implementations of "python-magic"
You appear to have installed python-magic-5.19.1, however, you reference firstly the documentation for python-magic-0.4.6, and secondly filemagic-1.6. I think that you are better off using python-magic-0.4.6 as it is readily available at PYPI and easily installed via pip into virtualenv environments.
Documentation for python-magic-5.19.1 is hard to come by, but I managed to get it to work like this:
>>> import magic
>>> m=magic.open(magic.MAGIC_NONE)
>>> m.load()
0
>>> m.file('/etc/passwd')
'ASCII text'
>>> m.file('/usr/share/cups/data/default.pdf')
'PDF document, version 1.5'
You can also get different magic descriptions, e.g. MIME type:
>>> m=magic.open(magic.MAGIC_MIME)
>>> m.load()
0
>>> m.file('/etc/passwd')
'text/plain; charset=us-ascii'
>>> m.file('/usr/share/cups/data/default.pdf')
'application/pdf; charset=binary'
or for more recent versions of python-magic-5.30
>>> import magic
>>> magic.detect_from_filename('/etc/passwd')
FileMagic(mime_type='text/plain', encoding='us-ascii', name='ASCII text')
>>> magic.detect_from_filename('/etc/passwd').mime_type
'text/plain'

Categories

Resources