如何使用Python运行短键?

我明白,我们可以使用subprocess来执行Linux Shell命令

import subprocess subprocess.call(["ls", "-l"]) 

如果我想在terminal上运行CTRL + C操作怎么办?

我的使用案例是:

  1> Open a linux screen 2> Run a command over first window 3> Then create a window in the same screen 4> Run another command over the second window 

这很明显,我想自动化我的日常工作的一部分。

啊哈! 找到了解决办法

如果你使用Ubuntu或回溯(基于Debian的Linux风格),那么你可以安装: apt-get install xautomation

对于喜欢使用英文编码的人来说,使用这种方法调用键击会容易一些,但稍微复杂一些:

 from subprocess import Popen, PIPE control_f4_sequence = '''keydown Control_L key F4 keyup Control_L ''' shift_a_sequence = '''keydown Shift_L key A keyup Shift_L ''' def keypress(sequence): p = Popen(['xte'], stdin=PIPE) p.communicate(input=sequence) keypress(shift_a_sequence) keypress(control_f4_sequence)