4

Iam new in information security and iam trying to teach my self how to build a simple keylogger with python, i found this code in a site :

import pythoncom, pyHook

def OnKeyboardEvent(event):
    print 'MessageName:',event.MessageName
    print 'Message:',event.Message
    print 'Time:',event.Time
    print 'Window:',event.Window
    print 'WindowName:',event.WindowName
    print 'Ascii:', event.Ascii, chr(event.Ascii)
    print 'Key:', event.Key
    print 'KeyID:', event.KeyID
    print 'ScanCode:', event.ScanCode
    print 'Extended:', event.Extended
    print 'Injected:', event.Injected
    print 'Alt', event.Alt
    print 'Transition', event.Transition
    print '---'

    # return True to pass the event to other handlers
    return True

# create a hook manager
hm = pyHook.HookManager()
# watch for all mouse events
hm.KeyDown = OnKeyboardEvent
# set the hook
hm.HookKeyboard()
# wait forever
pythoncom.PumpMessages()

and while i was trying to understand this code, i found the call of the function 'OnKeyboardEvent' without giving it's parameter

hm.KeyDown = OnKeyboardEvent

So my question is : is there a way in python to call a function without giving it the parameter ?

wael ashraf
  • 53
  • 1
  • 4

3 Answers3

5

in python a function name is equivalent to a variable in which a function is stored. in other words: you can define a function called foo and store / reference it in a second variable bar:

def foo():
    print("foo!")

bar = foo

bar() # prints: foo!

in your case, you are only defining the function OnKeyboardEvent(event) and you save a reference of it in hm.KeyDown

the call of the function happens only if you press a keyboard key and is called internally in hm from an event handler. and there the event handler passes down an event object to the function.

to answer your question concerning calling functions without their parameters. it's possible for functions where default values for all parameters are set e.g.:

def foo(bar = "default string"):
    print(bar)

print(foo()) # prints: default string
print(foo("hello world!")) # prints: hello world!
Philipp Lange
  • 851
  • 1
  • 6
  • 11
1

Calling a function:

OnKeyboardEvent()

Assigning a function to let's say a variable (this doesn't call the function immediately):

var = OnKeyboardEvent

and your is just assigning the function OnKeyboardEvent to pyHook.HookManager('s) KeyDown property

hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
Adrián Kálazi
  • 250
  • 1
  • 2
  • 13
0

when you do hm.KeyDown = OnKeyboardEvent you are not calling the function OnKeyboardEvent, you are just assign that function to hm.KeyDown. Later pyHook.HookManager will invoke that method for you when any KeyboardEvent happens.

gipsy
  • 3,859
  • 1
  • 13
  • 21