【问题标题】:Input unicode string with pyautogui使用 pyautogui 输入 unicode 字符串
【发布时间】:2016-01-14 02:35:19
【问题描述】:

我正在使用 pyautogui lib 创建一个自动测试应用程序。我想使用typewrite 方法将文本输入到表单中。但是我的一些输入字符串中包含 unicode 字符。例如:

最讨厌

根据文档typewrite 只能按单字符键。所以它只是忽略了æ 字符。

您能建议一些简单的解决方法吗?

【问题讨论】:

    标签: unicode pyautogui


    【解决方案1】:
    from pynput.keyboard import Controller
    import time 
    time.sleep(3)
    Controller().type("Næst")
    

    此代码完美运行。只需要使用 pip 命令安装 pynput。

    【讨论】:

      【解决方案2】:

      试试pynput,我发现输入 Unicode 文本更容易

      from pynput.keyboard import Controller
      
      keyboard = Controller()
      
      keybard.type("Næst")
      

      【讨论】:

        【解决方案3】:

        我尝试了trestlnord 的答案,但没有奏效。我将这个想法改编为:

        import pyautogui as px
        
        def type_unicode(word):
            for char in word:
                num = hex(ord(char))
                px.hotkey('ctrl', 'shift', 'u')
                for n in num:
                    px.typewrite(n)
                px.typewrite('\n')
        

        适用于arch linux

        【讨论】:

          【解决方案4】:

          我知道这个帖子很旧,但为了这个话题,我认为我设法以更简单的方式使用 pyperclip 绕过它。

          与其试图让 pyautogui 键入特殊字符,不如使用 pyperclip 将它们复制到剪贴板,然后使用 pyautogui 粘贴它们。例如在 Windows 上:

          import pyautogui
          import pyperclip
          
          pyperclip.copy("It's leviOsa, not lêvioçÁ!")
          pyautogui.hotkey("ctrl", "v")
          

          编辑:

          我们可以让它在多个平台上工作,如下所示(感谢@karlo 指出):

          import pyautogui
          import pyperclip
          import platform
          
          def type(text: str):    
              pyperclip.copy(text)
              if platform.system() == "Darwin":
                  pyautogui.hotkey("command", "v")
              else:
                  pyautogui.hotkey("ctrl", "v")
          
          
          type("It's leviOsa, not lêvioçÁ!")
          

          【讨论】:

          • 在 Max OS X 上,我不得不将粘贴行更改为 pyautogui.hotkey("command", "v")
          • 漂亮的例子
          【解决方案5】:

          找到一个很简单的。

          在 Mac 和 Linux 中,可以使用十六进制代码输入 unicode 字符。关于那个有article on wikipedia。我正在为 Mac 编写程序,因此我在键盘设置中启用了 Unicode Hex Input 并编写了以下代码:

          def type_unicode(word):
              for c in word:
                  c = '%04x' % ord(c)
                  pyautogui.keyDown('optionleft')
                  pyautogui.typewrite(c)
                  pyautogui.keyUp('optionleft')
          

          【讨论】:

            猜你喜欢
            • 2020-02-14
            • 2023-02-14
            • 1970-01-01
            • 1970-01-01
            • 2019-05-04
            • 1970-01-01
            • 1970-01-01
            • 2015-04-18
            • 2012-07-18
            相关资源
            最近更新 更多