问题
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
andshell=True
because screen returns a exit code of1
, which doesn't play well with thecheck_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