使用xvfb调用自身的python脚本

时间:2016-06-01 18:22:48

标签: python xvfb

我编写了一个用ete3 package生成系统发育树的脚本,该脚本在无头服务器上运行,因此必须使用xvfb-run(每here)启动。

我已设置脚本以检查(通过系统调用ps)是否使用xvfb调用它。在没有xvfb-run(例如python script.py...)的情况下启动python脚本的情况下,是否有一种简单的方法可以杀死进程并从中正确地重新运行它(例如xvfb-run python script.py...)原始剧本电话?

我已经尝试通过对os.system() ps的{​​{1}}电话进行黑客攻击,但我没有太多运气。有没有人有任何建议?

1 个答案:

答案 0 :(得分:1)

我能够将某些内容放在一起,只需将函数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 http://stackoverflow.com/a/6550543/1153897 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!'