2016-10-19 75 views
1

我正在嘗試做一個函數,它不斷打印出鼠標位置,直到停止。 進口pyautogui嘗試打印出鼠標位置時錯誤的輸出

import pyautogui 

print('Press CTRL + "c" to stop') 

while True: 
    try: 
     x, y = pyautogui.position() 
     positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4) 
     print(positionStr, end = ' ') 
     print('\b' * len(positionStr), end = '', flush = True) 
    except KeyboardInterrupt: 
     print('\nDone') 
     break 

預期的輸出應該是這個樣子:

X:265 Y:634 只有一條線不斷刷新

但是,這是我什麼取而代之:

XXXXXXXXXXXXXXXXXXX:665 Y:587

XXXXXXXXXXXXXXXXX:665 Y:587

XXXXXXXXXXXXXXXXXXXX:665 Y:587

XXXXXXXXXX:718 Y:598

XXXXXXXXXXXX:1268 Y:766

除去\ B個字符 import pyautogui

print('Press CTRL + "c" to stop') 

while True: 
try: 
    x, y = pyautogui.position() 
    positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4) 
    print(positionStr) 
    print('\b' * len(positionStr), end = '', flush = True) 
except KeyboardInterrupt: 
    print('\nDone') 
    break 

X:830 Y:543

X:830 Y:543

X:830 Y:543

X:830 Y:543

完成

+0

的輸出是什麼,如果你做不打印'\ b'字符? –

+0

更新了匹配的結果。它擺脫了重複的'x',但仍然不是潮紅 – MoRe

+0

你是什麼意思,它不是潮? –

回答

1

您不退格足夠的字符。你忘了考慮多餘的空間「結束」字符。當然,你應該完全可以忽略參數end

+0

那麼,如何增加我製作的退格的數量,我應該讓len(positionString)+1還是其他效果? – MoRe

+0

@ user7032374應該做的伎倆。或者,正如我在回答中所說的那樣,從前面的調用中刪除'end'參數。 –

+0

所以我擺脫了兩端,但它仍然沒有擦除線條。例如 – MoRe

3

您可以打印行用回車:

即:

print(positionStr + '\r'), 

像這樣,下一行會取代現有的。並且您將始終看到一行更新了新的鼠標位置。

完整的腳本:

#!/usr/bin/env python 

import pyautogui 

print('Press CTRL + "c" to stop') 

while True: 
    try: 
     x, y = pyautogui.position() 
     positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4) 
     print(positionStr + '\r'), 
    except KeyboardInterrupt: 
     print('\nDone') 
     break 

希望它能幫助。

編輯

正如下面的評論說,該解決方案將在Unix平臺的作品,但沒有對他人進行測試。它應該從不同的行結束約定開始。感謝@ Code-Apprentice指出了這一點。

重新編輯

由於OP和代碼學徒的意見,我試圖解決這樣的腳本和它的作品像預期:

import pyautogui 

print('Press CTRL + "c" to stop') 

while True: 
    try: 
     x, y = pyautogui.position() 
     positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4) 
     print(positionStr, end=' ') 
     print('\b' * (len(positionStr) + 1), end='') 
    except KeyboardInterrupt: 
     print('\nDone') 
     break 
+0

@volcano感謝您的編輯,但昏迷後,來右括號。 – JazZ

+0

對不起,搞砸了。需要更多的睡眠:-) – volcano

+0

無論如何。它更像這樣可讀。 =) – JazZ