Skip to content
Create a gist now

Instantly share code, notes, and snippets.

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Now this lib is on her own full repository and pypi page:
# This may not work with bpython, use python 2.6 or upper
# This program is free software. It comes without any warranty, to
# the extent permitted by applicable law. You can redistribute it
# and/or modify it under the terms of the GNU Public License 2 or upper.
# Please ask if you wish a more permissive license.
# Author: Christophe Narbonne
# Contrib: Alexis Metaireau
from commands import getoutput
from multiprocessing import Process
from os import system
from time import sleep
def list_screens():
"""List all the existing screens and build a Screen instance for each
return [Screen(".".join(l.split(".")[1:]).split("\t")[0])
for l in getoutput("screen -ls | grep -P '\t'").split('\n')]
class ScreenNotFoundError(Exception):
"""raised when the screen does not exists"""
class Screen(object):
"""Represents a gnu-screen object::
>>> s=Screen("screenName", create=True)
>>> s.exists
>>> s.state
>>> s.send_commands("man -k keyboard")
>>> s.kill()
>>> s.exists
def __init__(self, name, create=False): = name
self._id = None
self._status = None
if create:
def id(self):
"""return the identifier of the screen as string"""
if not self._id:
return self._id
def status(self):
"""return the status of the screen as string"""
return self._status
def exists(self):
"""Tell if the screen session exists or not."""
# output line sample:
# " 28062.G.Terminal (Detached)"
lines = getoutput("screen -ls | grep " +'\n')
return in [".".join(l.split(".")[1:]).split("\t")[0]
for l in lines]
def create(self):
"""create a screen, if does not exists yet"""
if not self.exists:
system('screen -UR ' +
def interrupt(self):
"""Insert CTRL+C in the screen session"""
system("screen -x " + + " -X eval \"stuff \\003\"")
def kill(self):
"""Kill the screen applications then quit the screen"""
system('screen -x ' + + ' -X quit')
def detach(self):
"""detach the screen"""
system("screen -d " +
def _delayed_detach(self):
def send_commands(self, *commands):
"""send commands to the active gnu-screen"""
for command in commands:
system('screen -x ' + + ' -X stuff "' + command + '" ')
system('screen -x ' + + ' -X eval "stuff \\015" ')
def _check_exists(self, message="Error code: 404"):
"""check whereas the screen exist. if not, raise an exception"""
if not self.exists:
raise ScreenNotFoundError(message)
def _set_screen_infos(self):
"""set the screen information related parameters"""
if self.exists:
infos = getoutput("screen -ls | grep %s" %'\t')[1:]
self._id = infos[0].split('.')[0]
self._date = infos[1][1:-1]
self._status = infos[2][1:-1]
def __repr__(self):
return "<%s '%s'>" % (self.__class__.__name__,
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.