如何杀死通过Python启动的无头X服务器?

2024-05-28 19:16:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用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服务器被杀死。我怎么能做到?在


Tags: theruningithubcomhttp网页sys
1条回答
网友
1楼 · 发布于 2024-05-28 19:16:18

^{}的文档说明:

These functions all execute a new program, replacing the current process; they do not return. [..]

因此,在调用os.execvp之后,程序中不会执行其他语句。您可能希望改用^{}

The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several other, older modules and functions, such as:

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

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

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

^{pr2}$

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

相关问题 更多 >

    热门问题