2016-02-19 146 views
1

我嘗試用python模擬鍵盤,我不知道如何處理多個鍵盤按鈕按下。下面的代碼工作在同一時間(FE「CTRL + C」)按1個或2鍵完美的罰款:有沒有辦法在python中動態創建/修改函數

if '+' in current_arg: 
    current_arg = current_arg.split('+') 
    current_arg[0] = current_arg[0].strip() 
    current_arg[1] = current_arg[1].strip() 

    SendInput(Keyboard(globals()["VK_%s" % current_arg[0].upper()]), 
       Keyboard(globals()["VK_%s" % current_arg[1].upper()])) 
    time.sleep(input_time_down()) 

    if len(last_arg) > 1 and type(last_arg) == list: 
     SendInput(Keyboard(globals()["VK_%s" % last_arg[0].upper()], KEYEVENTF_KEYUP), 
        Keyboard(globals()["VK_%s" % last_arg[1].upper()], KEYEVENTF_KEYUP)) 
     time.sleep(input_time_down()) 
    else: 
     SendInput(Keyboard(globals()["VK_%s" % last_arg.upper()], KEYEVENTF_KEYUP)) 
     time.sleep(input_time_down()) 

但是,如果有在同一時間按下3樓或更多的按鈕?什麼是最優雅的方式來做到這一點?如果'+'count == 2,如果'+'count == 3等,我可以添加,如果'+'count == 2,但必須有更好的方法來做到這一點。我希望我的函數能夠適應參數的數量。

例如:

keyboard_sim( 'CTRL + SHIFT + ESC'):

if '+' in current_arg: 
    current_arg = current_arg.split('+') 
    current_arg[0] = current_arg[0].strip() 
### function adds another current_arg for each argument 
    current_arg[1] = current_arg[1].strip() 
    current_arg[2] = current_arg[2].strip() 

    SendInput(Keyboard(globals()["VK_%s" % current_arg[0].upper()]), 
### function adds another Keyboard for each argument 
       Keyboard(globals()["VK_%s" % current_arg[1].upper()])) 
       Keyboard(globals()["VK_%s" % current_arg[2].upper()])) 
    time.sleep(input_time_down()) 

    if len(last_arg) > 1 and type(last_arg) == list: 
### function adds another Keyboard KEYEVENTF for each argument 
     SendInput(Keyboard(globals()["VK_%s" % last_arg[0].upper()], KEYEVENTF_KEYUP), 
        Keyboard(globals()["VK_%s" % last_arg[1].upper()], KEYEVENTF_KEYUP)) 
        Keyboard(globals()["VK_%s" % last_arg[2].upper()], KEYEVENTF_KEYUP)) 

     time.sleep(input_time_down()) 
    else: 
    ### this is added so I won't get error if there is single key pressed 
     SendInput(Keyboard(globals()["VK_%s" % last_arg.upper()], KEYEVENTF_KEYUP)) 
     time.sleep(input_time_down()) 
+1

是[this](http://stackoverflow.com/questions/3394835/args-and-kwargs)你需要什麼? – JETM

+0

編號我已經使用了參數,我希望函數根據分割後列表中有多少個參數進行更改。如果我想同時按下按鈕,我必須在單個SendInput(Keyboard()語句中使用它們,就像你上面看到的那樣,這個if語句已經在函數中了。 – Gunnm

回答

1

我不熟悉您正在使用,所以我假設他們是定製的SendInput /鍵盤的東西並由你撰寫。

假設SendInput就像def SendInput(*args)定義(由@JETM的建議),並說明:last_arg實際上應該current_arg,你應該能夠這樣稱呼它:

arglist = current_arg.split('+') 
# This will create a list of Keyboard objects 
keys = [KeyBoard(globals()["VK_%s" % key.upper()]) for key in arglist] 
# *keys splits the list of Keyboard objects so that SendInput receives 
# one entry in it's argument list for each Keyboard object in keys 
SendInput(*keys) 

利用這一點,內SendInput的ARGS變量將是每個鍵有一個Keyboard對象的列表。

+0

它工作的很好,謝謝你的幫助。 – Gunnm

相關問題