2

我想用 Python 获取网页的屏幕截图。为此,我正在使用http://github.com/AdamN/python-webkit2png/

    newArgs = ["xvfb-run", "--server-args=-screen 0, 640x480x24", sys.argv[0]]
    for i in range(1, len(sys.argv)):
        if sys.argv[i] not in ["-x", "--xvfb"]:
            newArgs.append(sys.argv[i])
    logging.debug("Executing %s" % " ".join(newArgs))
    os.execvp(newArgs[0], newArgs)

基本上用正确的参数调用 xvfb-run。但是man xvfb说:

Note that the demo X clients used in the above examples will not exit on their own, so they will have to be killed before xvfb-run will exit.

所以这意味着如果整个事情都在一个循环中,这个脚本将 <????> (获取多个屏幕截图),除非 X 服务器被杀死。我怎样才能做到这一点?

4

1 回答 1

5

状态的文档os.execvp

这些函数都执行一个新程序,替换当前进程;他们不回来。[..]

所以在调用之后os.execvp程序中没有其他语句将被执行。您可能想subprocess.Popen改用:

subprocess模块允许您生成新进程,连接到它们的输入/输出/错误管道,并获取它们的返回码。该模块旨在替换其他几个较旧的模块和功能,例如:

使用,在虚拟帧缓冲区 X 服务器subprocess.Popen中运行的代码变为:xlogo

import subprocess
xvfb_args = ['xvfb-run', '--server-args=-screen 0, 640x480x24', 'xlogo']
process = subprocess.Popen(xvfb_args)

现在的问题是在后台进程中xvfb-run启动。Xvfb调用process.kill()不会杀死Xvfb(至少不会在我的机器上......)。我一直在摆弄这个,到目前为止,唯一对我有用的是:

import os
import signal
import subprocess

SERVER_NUM = 99  # 99 is the default used by xvfb-run; you can leave this out.

xvfb_args = ['xvfb-run', '--server-num=%d' % SERVER_NUM,
             '--server-args=-screen 0, 640x480x24', 'xlogo']
subprocess.Popen(xvfb_args)

# ... do whatever you want to do here...

pid = int(open('/tmp/.X%s-lock' % SERVER_NUM).read().strip())
os.kill(pid, signal.SIGINT)

所以这段代码读取Xvfbfrom的进程 ID/tmp/.X99-lock并向进程发送中断。它可以工作,但会时不时地产生一条错误消息(不过我想你可以忽略它)。希望其他人可以提供更优雅的解决方案。干杯。

于 2009-11-18T11:41:38.807 回答