python 使用 xvfb 调用自身的脚本

python script to call itself with xvfb

我写了一个脚本,用 ete3 package, the script runs on a headless server thus it must be launched with xvfb-run (per here) 生成系统发育树。

我已经设置脚本来检查(通过对 ps 的系统调用)它是否是用 xvfb 调用的。如果 python 脚本在没有 xvfb-运行 的情况下启动(例如 python script.py...),我是否有一种直接的方法来终止进程并重新 运行 它从原始脚本调用中正确(例如 xvfb-run python script.py...)?

我试过通过 os.system() 调用 ps 来破解一些东西,但我运气不太好。有人有什么建议吗?

我能够将一些东西放在一起,只需将函数 check_xvfb() 添加到脚本的开头即可。

def check_xvfb():
    """
    Use of the ete3 library from the command line requires an X11 server
    which doesn't exist on this headless Ubuntu server.  One way around this
    is to use xvfb-run.  This function checks that the script was properly
    launched with xvfb-run; if not, it will relaunch it (with the same options)
    and then terminate the previously called script
                                                                                                                                           Parameters
    ----------                                                                                                                             none

    Returns
    -------
    none

    """

    # CHECK IF SCRIPT PROPERLY LAUNCHED
    # see  for explanation of 'cat'
    # grep -v ignores the ps -ef call since it'll match itself
    comm = 'ps -ef | grep xvfb-run | grep %s | grep -v grep | cat' %os.path.splitext(os.path.basename(sys.argv[0]))[0]
    output = subprocess.check_output(comm, shell=True)

    if not len(output): # script not called properly
        print 'script not called properly, retrying...'
        comm_run = 'xvfb-run ' + ' '.join(sys.argv)
        os.system(comm_run) # properly call script
        sys.exit(0)
    else:
        print 'script called properly!'