【问题标题】:Python script to run in background while capturing screenshots捕获屏幕截图时在后台运行的 Python 脚本
【发布时间】:2015-01-18 01:37:53
【问题描述】:

我创建了一些 python 代码来在访问某个站点时捕获屏幕截图。 当我从终端运行我的代码时,它运行良好并提供输出。当设置为 cron 作业或启动脚本时,它似乎不起作用。有什么问题?抱怨无法开始显示,但如何解决?代码如下。

#!/usr/bin/python2.7
import time
import subprocess
def get_current_status(netss):
    netss = subprocess.check_output(“ss -rt”, shell=True)
    if “facebook” in netss:
        out_put = subprocess.check_output(‘import -window root “/home/user/test/new_$(date +%F-%N).png”‘, shell=True)
        time.sleep(3)
    elif “youtube” in netss:
        out_put = subprocess.check_output(‘import -window root “/home/user/test/new_$(date +%F-%N).png”‘, shell=True)

     else:
        print(“Not yet time to capture”)

def main():
    get_current_status(“netss”)
while True:
    main()
    time.sleep(10)

【问题讨论】:

  • 你能粘贴你得到的确切错误吗?可能是因为 cron 作业尝试运行时显示器处于休眠状态?
  • 确切的错误是在图像捕获时无法显示。您可以在您的机器上尝试该代码并意识到它在终端中运行良好,但在设置为 cronjob 或作为服务运行时并非如此。当使用“update-rd.rc command defaults”设置为作为服务运行时,其中 command 是一个调用它的 shell 脚本,它会出现显示错误。你是什​​么意思显示睡着了?在测试模式下,您意识到捕获的间隔很短,因此显示没有休眠。
  • 我昨天让它运行起来了。我必须创建一个由 py​​thon 脚本调用的单独的 bash shell 脚本。 bash 脚本是捕获屏幕截图的脚本,它使用 xwd 并声明要捕获的显示。它看起来像这样; #!/bin/bash export DISPLAY=:0 && /usr/bin/xwd -display :0.0 -root -out file_name
  • 如果 xwd 命令直接从 python 脚本运行,只要显示参数是为登录的用户指示的,它也可以很好地工作。

标签: python linux debian


【解决方案1】:

我在 python3 中使用 subprocess.getoutput 并在 python 脚本中设置 DISPLAY 环境对其进行了整理。您也可以将此 python 脚本作为 cronjob 运行。当我在“python的类和对象”中深入了解时,我开发了这个看看下面的代码:

#!/usr/bin/env python3
import subprocess
import time
import pyscreenshot as ImageGrab
import os
if not 'DISPLAY' in os.environ:
    os.environ['DISPLAY'] = ":0"

class NewCapture:
    command = subprocess.getoutput("sudo ss -nt state established dst :443")
    file_name = time.strftime("%Y-%m-%d-%H-%M-%S" +".png")
    grab = ""
    def funct_capture(self):

        if ":443" in self.command:

            self.grab = ImageGrab.grab_to_file("/home/user/test/%s" % self.file_name)

        else:
            pass

firstcommand = NewCapture()
firstcommand.funct_capture()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    相关资源
    最近更新 更多