Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何创建在后台运行并对键盘输入作出反应的Python脚本?_Python_Windows_Python 3.x_Background Process - Fatal编程技术网

如何创建在后台运行并对键盘输入作出反应的Python脚本?

如何创建在后台运行并对键盘输入作出反应的Python脚本?,python,windows,python-3.x,background-process,Python,Windows,Python 3.x,Background Process,目前,我正在使用通过键盘快捷键触发脚本。比起处理自动热键,我更喜欢用Python编程。每当我接触自动热键脚本时,我希望我能简单地编写干净的自动热键代码 让我们看一下简单的自动热键脚本,当我按下insert键时,它会在我所在的任何窗口中打印hello world: foo(){ send, "hello world" } Insert:: foo() 如何在Windows上的Python3中执行相同的操作?您可以结合StackOverflow的两个答案来(几乎)解决这个问题 使用answ

目前,我正在使用通过键盘快捷键触发脚本。比起处理自动热键,我更喜欢用Python编程。每当我接触自动热键脚本时,我希望我能简单地编写干净的自动热键代码

让我们看一下简单的自动热键脚本,当我按下insert键时,它会在我所在的任何窗口中打印
hello world

foo(){
    send, "hello world"
}
Insert:: foo()

如何在Windows上的Python3中执行相同的操作?

您可以结合StackOverflow的两个答案来(几乎)解决这个问题

  • 使用answer(by)创建一个类似
    getch()
    的方法,从用户那里读入一个字符,而不需要
    \n
    。(答案重复如下)
  • 使用Python3版本的answer(by)在单独的进程中调用先前定义的
    \u Getch()
  • 请注意,以下代码仅适用于Python3,并使用任何键来停止进程,而不仅仅是插入键

    # This code is a combination of two StackOverflow answers
    # (links given in the answer)
    
    # ------- Answer 1 by tehvan -----------------------------------
    class _Getch:
        """Gets a single character from standard input.  
           Does not echo to the screen."""
        def __init__(self):
            try:
                self.impl = _GetchWindows()
            except ImportError:
                self.impl = _GetchUnix()
    
        def __call__(self): return self.impl()
    
    class _GetchUnix:
        def __init__(self):
            import tty, sys
    
        def __call__(self):
            import sys, tty, termios
            fd = sys.stdin.fileno()
            old_settings = termios.tcgetattr(fd)
            try:
                tty.setraw(sys.stdin.fileno())
                ch = sys.stdin.read(1)
            finally:
                termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
            return ch
    
    class _GetchWindows:
        def __init__(self):
            import msvcrt
    
        def __call__(self):
            import msvcrt
            return msvcrt.getch()
    
    getch = _Getch()
    
    # -------- Answer 2 by Barafu Albino (modified) -------
    import _thread
    
    def input_thread(a_list):
        _Getch().__call__()
        a_list.append(True)
    
    def do_stuff():
        a_list = []
        _thread.start_new_thread(input_thread, (a_list,))
        print('Press any key to stop.')
        while not a_list:
            pass  
            # This is where you can put the stuff 
            # you want to do until the key is pressed
        print('Stopped.')
    
    do_stuff()
    

    要实现这一点,你必须把它挂在窗户上。您可能必须通过
    ctypes
    或模块来实现这一点,因为中似乎不存在必要的API

    根据,您将需要使用三个windows API调用:

    • ,使用
      idHook
      WH\u键盘LL设置键盘挂钩;查看键盘事件的函数
    • 最终取下钩子
    • 如果你对某个按键不感兴趣,把它传给下一个钩子

    如果不重写自动热键,您可能无法执行此操作。主要问题是焦点,AHK似乎会扫描所有输入以查找其热键,这是纯Python程序无法做到的,因为它只在自己的窗口具有焦点时接收输入。您还必须依赖macOS或linux下的特殊(但不同)系统挂钩。换句话说,AHK正在做一些非琐碎的工作,以便在系统看到之前将所有输入活动发送出去。@msw:我承认我还不能做,但这项任务在我看来还不够奇特,以至于我是唯一希望能够做的人,因此,如果没有库,那就很奇怪了。也许可以编写一个解析器,然后将Python编译成AHK的脚本语言?或者您可以使用运行macroexamples.pyw-。pyw扩展可以运行Python脚本,而无需关注windows本身。insert::运行“c:\macro1.pyw”return-然后您可以发送任何文本或键盘快捷键宏移动,并且当我通过命令行启动脚本时,它在不处于焦点时不会执行任何操作。Oops。没错。这不会失去焦点。当我试图找到解决办法时,我会暂时保留这个答案。