通过Python从命令窗口读取内容

2 投票
2 回答
3132 浏览
提问于 2025-04-17 03:10

我想要连接到一个已经打开的命令提示符窗口,并读取里面的内容。

这个命令提示符窗口是随便打开的,不是我自己创建的子进程。

有没有什么方法可以用Python来实现这个?

提前谢谢你,

Omer。

2 个回答

0

这可以通过使用pywinauto、pytesseract和PIL来实现。你只需要用pywinauto检查窗口是否存在,然后截取它的屏幕截图。接着,使用tesseract和PIL读取图片中的文字。下面的代码示例就是这样做的 -

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])

示例输出 - 文件创建的日期 -

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

你需要安装 -

pip install pillow
pip install pytesseract
pip install pywinauto
2

** 注意:原问题的版本是问如何同时读取和写入命令窗口 **

写入

你可以用一些代码向已经打开的命令窗口写入内容,比如:

from pywinauto import application

app = application.Application()

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

注意事项:

  1. 我通过以下命令在Python 2.6的环境中安装了最新版本的pywinauto:

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

  2. 我建议不要仅仅依赖cmd.exe的路径,最好让程序更健壮一些!关于如何选择应用程序的文档可以在这里找到。

读取

从已经打开的命令窗口读取内容似乎要复杂一些!在pywinauto-users邮件列表上,有人已经成功实现了这个功能,并愿意分享一个可用的示例:http://thread.gmane.org/gmane.comp.python.pywinauto.user/249/focus=252,我建议你联系他。

撰写回答