python控制台终端应该位于任何窗口的顶部



我想听听你的意见和支持,我正在努力克服一个问题。这将是我正在建设的一个小项目完成的最后一块拼图。它基于OCR。我正在阅读文本从一个实时屏幕(使用下面的python脚本),并能够得到的结果登录到一个文件。然而,只有当我使用alt+tab键使python控制台窗口(脚本在其中打印输出)激活/聚焦时,输出才会被记录。

但是这样做会阻止软件从我阅读文本的地方,破坏整个过程。将窗口切换到软件的前面是脚本目的的失败。

所以,我添加了代码后,从其他用户搜索关于保持python控制台窗口总是在顶部,无论软件正在做什么。我无法保持这个python控制台窗口在这个软件屏幕的顶部。SW使用所有屏幕用于其工作目的。

有其他选择吗?我如何使python控制台成为任何其他窗口的顶部,无论屏幕上是什么?如果不是这样,请建议一个替代方案。

import numpy as nm
from datetime import datetime
import pytesseract
import cv2
import PIL
from PIL import ImageGrab
import win32gui, win32process, win32con
import os
hwnd = win32gui.GetForegroundWindow()
win32gui.SetWindowPos(hwnd,win32con.HWND_TOPMOST,0,0,100,300,0) 
#Define function for OCR to enable on multiple screens. 
def imToString(): 
# Path of tesseract executable
pytesseract.pytesseract.tesseract_cmd ='C:\Tesseract-OCR\tesseract.exe'
while(True):

# ImageGrab-To capture the screen image in a loop.
# Bbox used to capture a specific area.
#screen base
cap1 = PIL.ImageGrab.grab(bbox =(0, 917, 1913, 1065), include_layered_windows=False, all_screens=True)
date = datetime.now().strftime("%Y-%m-%d %I:%M:%S")    
#str config - OCR Engine settings for ONLY text based capture.
config1 = ('-l eng --oem 2 --psm 6')

#configuring tesseract engine for OCR 
tess1 = pytesseract.image_to_string(
cv2.cvtColor(nm.array(cap1), cv2.COLOR_BGR2GRAY),
config=config1)

#Defining log pattern to generate
a = [ date, " State: ", tess1 ]

#writing logging output to file
file1 = open("C:\Users\User\Desktop\rev2.log", "a", encoding='UTF8')
file1.writelines(a)
file1.writelines("n")
file1.close()                                       
#OUTPUT on colse for Logging verification
print (date, "State: ", tess1)  


# Calling the function
imToString()

根据要求,我不允许在操作屏幕时使用键盘。我是相当新的python和已经看到类似的解决方案,并将其添加到脚本,使一个适当的解决方案。

请建议。

tkinter方法:

from tkinter import Tk, Text
import subprocess
import threading
from queue import Queue, Empty

filename = 'test.py'

def stream_from(queue):
command = f'python {filename}'
with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as process:
for out in process.stdout:
queue.put(out.decode())

def update_text(queue):
try:
data = queue.get(block=False)
except Empty:
pass
else:
text.config(state='normal')
text.insert('end', data.strip() + 'n')
text.config(state='disabled')
finally:
root.after(100, update_text, queue)

def loop():
root.attributes('-topmost', True)
root.after(1, loop)

root = Tk()

text = Text(root, state='disabled')
text.pack()
data_queue = Queue()
threading.Thread(target=stream_from, args=(data_queue, ), daemon=True).start()
update_text(data_queue)
loop()
root.mainloop()

只需将filename更改为您正在运行的文件的名称,并将此脚本放在同一目录中
更改delay_in_ms(以毫秒为单位的延迟,因此每1000个单位是一秒),看看是否有帮助(也可以离开10秒,看看它现在是否有效,如果没有,还有另一件事要尝试)

如果你使用print输出,那么这应该工作(虽然我可能没有得到你想要的),如果你使用logging,那么有一个稍微不同的解决方案

最新更新