如何在Python中将一些字符串粘贴到活动窗口?

时间:2010-06-16 06:01:44

标签: python windows sendkeys

  

可能重复:
  How do I copy a string to the clipboard on Windows using Python?

有人能让我举个例子或向我解释如何用Python将东西粘贴到活动窗口?

1 个答案:

答案 0 :(得分:2)

如果您使用SendKeys,这是最简单的方法。您可以找到各种Python版本here的Windows安装程序。

最简单的用例,发送纯文本,非常简单:

import SendKeys
SendKeys.SendKeys("Hello world")

你可以做各种漂亮的事情使用键码代表不可打印的字符

import SendKeys
SendKeys.SendKeys("""
    {LWIN}
    {PAUSE .25}
    r
    Notepad.exe{ENTER}
    {PAUSE 1}
    Hello{SPACE}World!
    {PAUSE 1}
    %{F4}
    n
""")

阅读the documentation了解详情。

如果由于某种原因你不想引入对非标准库包的依赖,你可以do the same thing使用COM:

import win32api
import win32com.client

shell = win32com.client.Dispatch("WScript.Shell")
shell.Run("calc")
win32api.Sleep(100)
shell.AppActivate("Calculator")
win32api.Sleep(100)
shell.SendKeys("1{+}")
win32api.Sleep(500)
shell.SendKeys("2")
win32api.Sleep(500)
shell.SendKeys("~") # ~ is the same as {ENTER}
win32api.Sleep(500)
shell.SendKeys("*3")
win32api.Sleep(500)
shell.SendKeys("~")
win32api.Sleep(2500)