我创建了一些 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)
最佳答案
我使用 python3 中的 subprocess.getoutput 并在 python 脚本中设置 DISPLAY 环境来解决它。您也可以将这个 python 脚本作为 cronjob 运行。我在“python的类和对象”中获取gr.ounded的过程中开发了这个,请看下面的代码:
#!/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()
关于在捕获屏幕截图时在后台运行的 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28006311/