以 root 身份运行 pyscreenshot

时间:2021-02-05 00:31:17

标签: python linux sudo

我正在尝试编写一个小的 python 脚本,它将抓取屏幕的一部分,检查它是否包含某种颜色的像素,如果是,则使用“键盘”包编写“foo”并单击 Enter .

我的问题是:要使用“键盘”,脚本必须以 root 身份运行,但这样做会以某种方式破坏屏幕抓取部分(如果我用 im.show() 检查它,它是全黑的),所以脚本只是循环并休眠而不做任何事情。

这些是我的代码的相关片段:

from time import sleep
import keyboard
import pyscreenshot as psc

while True:
    useKB = False
    im = psc.grab(bbox=(x0,y0,x1,y1)) #grab screen area
    rgb_im = im.convert('RGB') #convert image to rgb

    for y in range(0,y1-y0):
        for x in range(0,x1-x0):
            r,g,b = rgb_im.getpixel((x,y))
            if r==3 and g==251 and b==73: #found pixel
                useKB = True
                break;
        if useKB == True:
            break
    
    if useKB == True:
        #if I comment this 2 lines out and run without sudo, the script works as intended.
        keyboard.write('foo')
        keyboard.press_and_release('enter')
    
    sleep(1)

谢谢大家。

0 个答案:

没有答案