Search code examples
pythonfilepynput

pynput keyboard.type() interference


so i am having some trouble with my code where it recognizes keyboard.type() as a type instead of a string i have all the necessary imports. how can i fix this?

with open("words.txt") as fp:  
        line = fp.readline()
        cnt = 1
        while line:
                print(line)
                line = fp.readline()

                cnt += 1
                exploit(line)

def exploit(keyboard):
    time.sleep(2)
    keyboard.type(line)

error:

File "C:\Users\User\Desktop\ref.py", line 63, in start
    exploit(line)
  File "C:\Users\User\Desktop\ref.py", line 46, in exploit
    keyboard.type("hello")
AttributeError: 'str' object has no attribute 'type'

keyboard modual(https://pypi.org/project/pynput/) is imported


Solution

  • I'm assuming you have an import keyboard line that you're not showing us. (Next time, please provide a complete MCVE).

    The problem is on this line:

    def exploit(keyboard):
    

    The keyboard module will not be accessible within this function because its name has been overwritten with the keyboard parameter you have defined here. If you called exploit("Hello"), for example, then this code would attempt to execute "Hello".type(line). But the string has no method named type. You probably meant to use the name line instead.

    def exploit(line):
        time.sleep(2)
        keyboard.type(line)
    

    You may be under the impression that a function needs to declare which modules it uses in its signature. This is not the case. Modules imported at the top of your file will be accessible everywhere in that file without you having to do anything special.