开发者

reading content from a cmd window via python

I'm trying to connect to开发者_开发技巧 an existing cmd window and read its content.

It is an arbitrary cmd window and not a child process.

Any ideas how this can be done with python?

Thanks in advance, Omer.


** Note: the original version of the question asked how to read AND write to a cmd window **

Writing

You can write to an existing command window with code such as:

from pywinauto import application

app = application.Application()

app.connect_(path= r"C:\WINDOWS\system32\cmd.exe")
dlg = app.top_window_()
dlg.TypeKeys('hello world')

Notes:

  1. I installed the latest version of pywinauto into a Python 2.6 installation direct from the Mercurial repository with the command:

    pip install -e hg+https://code.google.com/p/pywinauto/#egg=pywinauto

  2. I would make this rather more robust than assuming the path to cmd.exe! Documentation on selecting the application is at http://pywinauto.googlecode.com/hg/pywinauto/docs/HowTo.html

Reading

Reading from an existing command window appears to be somewhat more difficult! Someone on the pywinauto-users mailing list has got it working & is offering to post a working example: http://thread.gmane.org/gmane.comp.python.pywinauto.user/249/focus=252 I suggest you get in touch with him.


This is possible using pywinauto, pytesseract and PIL, What all you need to do is check for the window existence using pywinauto and take its screenshot. And read the text of the image using tesseract and PIL. Like in below code sample -

from pywinauto import Application, Desktop
from pytesseract import pytesseract
import time
from PIL import Image

app = Application(backend="uia").start(r'c:\WINDOWS\System32\cmd.exe /k', create_new_console=True, wait_for_idle=False)
time.sleep(3)
# grab the arbitrary window
calc = Desktop(backend="uia").window(title='c:\WINDOWS\System32\cmd.exe')
# print the dump tree (control identifiers) of the window
calc.dump_tree()

# type command and hit enter 
calc.type_keys("dir")
calc.type_keys('{ENTER}')

# select the window for taking screenshot
textarea = calc.child_window(title='Text Area')
textarea.set_focus()
textarea.draw_outline()
img = textarea.capture_as_image()
img.save('CMD_screenshot.png')

# Read the image using tesseract
path_to_tesseract = r"C:\Users\user-name\AppData\Local\Tesseract-OCR\tesseract.exe"
image_path = r"CMD_screenshot.png"
img = Image.open(image_path)
pytesseract.tesseract_cmd = path_to_tesseract
text = pytesseract.image_to_string(img)

# Displaying the extracted text
print(text[:-1])

sample output - dates of the file created -

08/24/2022
8/11/2022
06/14/2022
7/05/2022
7/06/2022

you will need to install -

pip install pillow
pip install pytesseract
pip install pywinauto
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜