Python and Curses, mangled mess

Posted on 2006-10-31
Last Modified: 2007-12-19
I'm fairly new to Python and completely confused when it comes to Curses. Perhaps an expert here can lend me a helping hand as I'm having a heck of a time trying to get any reason out of Curses.. the documentation for it is vague and not very helpful to me anymore, I can only ever seem to get the same couple of guides a million times on Google, so if anyone has any good tutorials or examples of this python socket curses client, that'd be nice too.

I am making a 3rd party client for a game. This game is typically graphical, however this client will be text only. I need a big huge window for a chat buffer and an input box below it for inputting text. The game is pretty much just a chat program, so the buffer will be filled with lots of "He says: Hi" and "She says: Bye".

My code so far is below... I was so frustrated I got rid of the bottom input box and just made it all the same.. I guess my main questions would be:
1. How can I add "scrolling", such that text does not get overwritten in the same spot in the output window all the time. I want each new line to be at the bottom and all lines before it to move up.
2. Please please please show me how to seperate the text input window from the output text window.
3. Any other hints or help would be appreciated!

from socket import *
import thread
import curses
import traceback

win = curses.initscr()
max_y, max_x = win.getmaxyx()
begin_x = 1 ; begin_y = 1
win = curses.newwin(max_y-1, max_x-1, begin_y, begin_x)
fsocket = socket(AF_INET, SOCK_STREAM)
ADDR = ('', 80)
fsocket.send("connect Username password\n")
def readdata():
        while 1:
                data = fsocket.recv(1024)
                        data = ""
while 1:
        data = win.getstr(0,0)
        fsocket.send(data + "\n")
Question by:Tabris42
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 29

Expert Comment

ID: 17847889
Curses were designed in the middle age of computers. The main goal is to move the cursor to line Y and position X on the screen, type a character here (possibly some special character) and set the colour of the text or of the background on that position (simplified). It was clear at that time that each character occupies box of exactly same size. You could not change the font size nor the font face. You often could not change the number of lines and the number of charactes on the line.

In my opinion, you do not want to use curses for your purpose if you use _also_ another graphical window. You should focus on creating a normal GUI window using Tkinter, wxPython, wax or some similar framework. I would recommend the wxPython + wax. Then create a window with one big TextBox for collected texts and one smaller below for entering text.

Have a look at wax primer ( that in steps shows how to write a simple text editor on 70 lines of code. After understanding that, you will be able to write you chat-like window. Inside TextBox, you can use various fonts, colors, etc.

For wax, you have to download and install wxPython and the wax. But it is pretty easy.
LVL 29

Expert Comment

ID: 17848051
See also another page related to wax
There is also the project on SourceForge

You can try the following quick hack -- two windows that you can type in, but no added functionality (just to start):

from wax import *

FIXED_FONT = ('Courier New', 10)

class MainFrame(Frame):

    def Body(self):

        vPanel = Panel(self, direction='vertical')

        self.bigTextBox = TextBox(vPanel, multiline=True, wrap=False)
        vPanel.AddComponent(self.bigTextBox, expand='both')

        self.smallTextBox = TextBox(vPanel, multiline=True, wrap=True)
        vPanel.AddComponent(self.smallTextBox, expand='h')

        self.AddComponent(vPanel, expand='both')

app = Application(MainFrame, title='My title')

Author Comment

ID: 17851495
That's nifty and something I may use another time but for this specific application I need to run from a terminal (like through PuTTy).. this is why I need curses (or something like it), to be able to seperate input from output while still using the command line interface..
[Webinar] Learn How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them. Thursday, July 13, 2017 10:00 A.M. PDT

LVL 29

Expert Comment

ID: 17856024
Frankly, I have never programmed using curses. I guess that you have looked at the curses module standard documentation and found also the URL for "Curses Programming with Python" It would probably be better to ask in Unix Prog. or Linux Prog. channel, because curses are probably used mainly on unixes.

The following documets also seems to be interesting. (They deal with ncurses, but as far as I know it is a superset of the older curses which is already implemented in the Python curses module.)

Good luck

Expert Comment

ID: 17856094
Hi, I have written a small class which may be of use to you, I hope it helps.

#! /usr/bin/python
import curses, os, sys
class Start:
    def __init__(self):
        if == "y": self.doProcess()
    def doDialog(self, event=None):
        win = self.createWindow(10, 2, 60, 15)    # x, y, w, h
        win.addstr(1, 24, "Primary Setup", curses.A_REVERSE)
        win.addstr(3, 1, "New Installation (y/n):")
        win.addstr(4, 1, "Date and Time (MMDDHHMM):")
        win.addstr(13, 1, "Continue (y/n):") = self.inputString(win, 3, 30, 1, ("in", (chr(27), "y", "n")))
        if == chr(27):
            sys.exit()  = self.inputString(win, 4, 30, 8, ("notblank",)) = self.inputString(win, 13, 30, 1, ("in", ("y", "n")))
    def createWindow(self, x, y, w, h):
        return curses.newwin(h, w, y, x)
    def createBox(self, scr, x, y, w, h):
        scr.addch(y, x, curses.ACS_ULCORNER)
        scr.addch(y, (x + w - 1), curses.ACS_URCORNER)
        scr.addch((y + h - 1), x, curses.ACS_LLCORNER)
        scr.addch((y + h - 1), (x + w - 1), curses.ACS_LRCORNER)
        scr.vline((y + 1), x, curses.ACS_VLINE, (h - 2))
        scr.hline(y, (x + 1), curses.ACS_HLINE, (w - 2))
        scr.vline((y + 1), (x + w - 1), curses.ACS_VLINE, (h - 2))
        scr.hline((y + h - 1), (x + 1), curses.ACS_HLINE, (w - 2))

    def inputChar(self, w, y, x, l=1):
        c = ""
        for x in range(x, (x+l)):
            i = w.getch(y, x)
            if i == 10: break
            c += chr(i)
        return c

    def inputString(self, w, y, x, l, verify=None):
        def doInput(w, y, x, l, verify):
            c = w.getstr(y, x, l)
            if not verify: return c
            if verify[0] == "notblank" and c: return c
            if verify[0] == "in" and c in verify[1]: return c
            if verify[0] == "dir" and os.path.isdir(c): return c
        c = None
        while c == None: c = doInput(w, y, x, l, verify)
        return c

    def endCurses(self):

    def doProcess(self):
        # Do whatever you want with the input

if __name__ == "__main__":

LVL 14

Accepted Solution

RichieHindle earned 500 total points
ID: 17905980
There are much higher-level libraries that curses for this kind of thing.  One of them is urwid - here's roughly the program you describe, implemented using urwid.  It provides automatic scrolling as you describe, and also provides scrollback using the Up and Down keys.  It resizes as you resize your terminal window as well.  It's a simplified version of the urwid IRC example here:


import urwid.curses_display
import urwid

class Screen:
    def __init__(self, tui): = tui

    def addLine(self, text):
        self.listbox.set_focus(len(self.lines) - 1)

    def redisplay(self):
        canvas = self.frame.render(self.size, focus=True), canvas)

    def run(self):
        self.size =
        self.lines = [urwid.Text('Hello')]
        self.listbox = urwid.ListBox(self.lines)
        self.input = urwid.Edit()

        self.frame = urwid.Frame(self.listbox, footer=self.input)


        while 1:
            keys =

            for key in keys:
                if key == 'window resize':
                    self.size =
                elif key == 'enter':
                    text = self.input.get_edit_text()
                elif key in ('up', 'down', 'page up', 'page down'):
                    self.listbox.keypress(self.size, key)
                    self.frame.keypress(self.size, key)


if __name__ == '__main__':
    tui = urwid.curses_display.Screen()
    screen = Screen(tui)

Author Comment

ID: 17908454
That is exactly the kind of thing I'm looking for. Thanks a lot!

Featured Post

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The really strange introduction Once upon a time there were individuals who intentionally put the grass seeds to the soil with anticipation of solving their nutrition problems. Or they maybe only played with seeds and noticed what happened... Som…
Variable is a place holder or reserved memory locations to store any value. Which means whenever we create a variable, indirectly we are reserving some space in the memory. The interpreter assigns or allocates some space in the memory based on the d…
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question