Python结合SAP GUI Script操作SAP

taishanduba 2020-04-29

想通过Python控制SAP。基于下面的网址实现的。感谢NewJune 提供了很有用的信息。

https://www.cnblogs.com/new-june/p/NewJune.html#commentform

下面的代码实现了,Python多进程的方式去调用SAP GUI。

多进程multiprocessing

在多线程里面使用win32com调用com组件的时候,需要用pythoncom.CoInitialize()初始化一下.

import sys
import win32com.client
import time
import pythoncom
from multiprocessing import Pool
from multiprocessing import freeze_support

def call_sapgui(sessionID):
    try:
        SapGuiAuto = win32com.client.GetObject("SAPGUI")
        if not type(SapGuiAuto) == win32com.client.CDispatch:
            return
        application = SapGuiAuto.GetScriptingEngine
        if not type(application) == win32com.client.CDispatch:
            SapGuiAuto = None
            return
        connection = application.Children(0)
        if not type(connection) == win32com.client.CDispatch:
            application = None
            SapGuiAuto = None
            return
        session = connection.Children(sessionID)
        if not type(session) == win32com.client.CDispatch:
            connection = None
            application = None
            SapGuiAuto = None
            return

        session.findById("wnd[0]/tbar[0]/okcd").text = "/nst03n"
        session.findById("wnd[0]").sendVKey(0)
        session.findById("wnd[0]/shellcont/shell/shellcont[1]/shell").expandNode("B.999")
        session.findById("wnd[0]/shellcont/shell/shellcont[1]/shell").topNode = "B"

    except Exception as error_msg:
        with open("error.txt", "a+") as f:
            print(error_msg,file=f)
    finally:
        session = None
        connection = None
        application = None
        SapGuiAuto = None


def Main():
    pythoncom.CoInitialize()
    po = Pool(3)#开启3个进程池
    for sessionID in range(3):
        po.apply_async(call_sapgui,(sessionID,))
    po.close() #关闭进程池,关闭后po不再接收新的请求。
    po.join() #等待po中所有子进程执行完成,必须放在close语句之后。

if __name__ == "__main__":
    Main()

相关推荐