0

I know how to print one line in same plase but I want to print same place from thread only.

Now I'm getting:

OK 97035 

I want to get:

OK 97035 
OK 92035

First line is from t1 thread, second from t2 thread. Anyone know how to do it ?

This is sample code.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import string, threading

def test():
    for i in range(0, 100000):
        print "\rOK "+str(i),

jczyd= ['1', '2']


while True:
        for i in jczyd:
                if i == '1':
                        #print i
                        t1 = threading.Thread(target=test, args = ())
                        t1.daemon = True
                        t1.start()
                elif i == '2':
                        #print i
                        t2 = threading.Thread(target=test, args = ())
                        t2.daemon = True
                        t2.start()
        t1.join()
        t2.join()
devbgs
  • 67
  • 2
  • 7
  • possible duplicate of [python print end=' '](http://stackoverflow.com/questions/2456148/python-print-end) – njzk2 Nov 28 '14 at 18:31
  • I saw this, but there are only print on same line but how to print in other lines text from other thread. – devbgs Nov 28 '14 at 18:35
  • The problem is the display is global resource, so you need a `lock` to control access to it. See the `print_lock` variable in [this answer](http://stackoverflow.com/a/18283388/355230) of mine for example. – martineau Nov 28 '14 at 18:35
  • 1
    This has nothing to do with display locking, `print(end=' ')`, or anything like that. This is a problem of continuously updating the display in two different places. – nneonneo Nov 28 '14 at 18:36
  • @nneonneo: Updating the display in two different places (threads) is exactly what adding a `lock` to the display would prevent. – martineau Nov 28 '14 at 18:39
  • @nneonneo: Yes, that's exactly what I meant. :) – devbgs Nov 28 '14 at 18:43

1 Answers1

1

Actually, this is trickier than you might think.

The problem is that there's no character in plain ASCII that you can use to update two separate lines of text simultaneously. \r only lets you erase one line.

If you want to update two lines you will have to use a platform-specific method, like ANSI escape codes, or use curses to control the terminal in a more general way.

On most UNIX systems, you can do this with code like this:

print '\x1b[%dH%s\x1b[K' % (thread_id, i)

which sets the cursor to the thread_idth line, prints i, then erases the rest of the line.

nneonneo
  • 171,345
  • 36
  • 312
  • 383
  • Or you could try to print both in one line and polling for the variables from the main thread. – wenzul Nov 28 '14 at 18:37
  • What I should put into `thread_id` ? I put `1` and have this error `TypeError: test() argument after * must be a sequence, not int` – devbgs Nov 28 '14 at 18:52
  • There's no `*` anywhere in my code: this is something else. – nneonneo Nov 28 '14 at 18:55