How to check screen is running?

无人久伴 提交于 2019-12-12 19:27:48

问题


How to check in Python whether the screen with the given name. For example, check if server1 is running?

Thanks : )


回答1:


The built in command for finding current screen sessions is screen -ls

To get the same functionality in python:

from subprocess import check_output

def screen_present(name):
        var = check_output(["screen -ls; true"],shell=True)
        if "."+name+"\t(" in var:
                print name+" is running"
        else:
                print name+" is not running"

screen_present("server1")

A couple of comments on the code:

  • I had to use ; true and shell=True because screen returns a exit code of 1, which doesn't play well with the check_output function.
  • Also, I added the "."+ and +\t( to make sure that we were matching the screen name and not another part of the printout.



回答2:


you could use subprocess and pgrep:

import subprocess

p = subprocess.check_output(['pgrep', '-f', 'screen'])
print p



回答3:


First off, what are you trying to achieve? You know that you can simply reattach a running screen session, do you?

screen -DRS admin # creates a new session if it isn't running

Likewise use screen -x -S admin to share the admin session without force-detaching the connected user(s).


Direct answer:

You can simply use the output of

screen -ls

which lists all running sessions, showing whether they are attached as well:

There are screens on:
        6675.third      (11/04/2011 09:25:49 PM)        (Attached)
        6668.pts-2.koolu        (11/04/2011 09:25:38 PM)        (Attached)
        6644.admin      (11/04/2011 09:25:21 PM)        (Detached)
3 Sockets in /var/run/screen/S-sehe.


来源:https://stackoverflow.com/questions/8015163/how-to-check-screen-is-running

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!