Hello experts:
I am now using SAP GUI Scripting to automatically download documents, using transaction code CV04N.
The script has been written by Python, but it needs to be optimized.
Here is the script:
—————————————————————————————
import win32com.client
import time
import pyautogui
import pandas as pd
# set path
file_path = r”C:UsersAdministratorDesktoptesttdocument_codes.xlsx”
# read Excel
df = pd.read_excel(file_path, engine=’openpyxl’)
document_codes = df[‘DocumentCode’].tolist()
try:
# Connect to SAP GUI
sap_gui_auto = win32com.client.GetObject(“SAPGUI”)
application = sap_gui_auto.GetScriptingEngine
connection = application.Children(0)
session = connection.Children(0)
# print(f”Connected to SAP session: {session.Info.SystemName}”)
# Start CV04N
session.StartTransaction(“CV04N”)
# print(“Navigated to transaction CV04N”)
for document_code in document_codes:
try:
# Input document code
session.findById(“wnd[0]/usr/tabsMAINSTRIP/tabpTAB1/ssubSUBSCRN:SAPLCV100:0401/subSCR_MAIN:SAPLCV100:0402/ctxtSTDOKNR-LOW”).text = document_code
time.sleep(1)
# Search
session.findById(“wnd[0]/tbar[1]/btn[8]”).press()
print(f”Document code {document_code} posted.”)
time.sleep(5) # Waiting for server
# Open Display Document: Basic Data Engin
session.findById(“wnd[0]”).sendVKey(45)
# print(“Show Info.”)
time.sleep(5)
session.findById(“wnd[0]”).maximize()
time.sleep(1)
# Save as
pyautogui.hotkey(‘shift’, ‘f7’, interval=0.5)
# print(“Shift + F7 pressed successfully.”)
time.sleep(3)
pyautogui.hotkey(‘enter’, interval=0.5)
# print(“Enter key pressed successfully.”)
time.sleep(10)
print(“Document Saved Successfully.”)
# Back to CV04N:Find Document: Select Criteria
# print(“Returning to CV04N interface for the next document.”)
session.findById(“wnd[0]/tbar[0]/btn[15]”).press()
# Press Back button
time.sleep(2)
session.findById(“wnd[0]/tbar[0]/btn[15]”).press()
# Press Back button
except Exception as e:
print(f”Error processing document {document_code}: {e}”)
continue
except Exception as e:
print(“Error during SAP automation:”, e)
————————————————————
When the document is downloaded, press Back button to return to the Find Document: Select Criteria interface and enter another document code to download.As shown below
However, due to server delays, I am not sure when the download will be completed, so using time.sleep() will cause problems.
Later, I found that when the file is downloaded, the GuiStatusbar will prompt “*** bytes passed”, and double-click this text, open another window, it shows “Message no. FES034”.
Can I detect this Message code to determine that the document has been downloaded, so as to perform the Back operation,so I don’t have to use time.sleep(). If so, how to write the code?
Or are there other detection methods to reduce the use of all time.sleeep() in the program?
Please help me, experts, thanks!