Python多进程控制SAP
想通过Python控制SAP。基于下面的网址实现的。感谢NewJune 提供了很有用的信息。
https://www.cnblogs.com/new-june/p/NewJune.html#commentform
关于以下代码,先说结果: 基本没什么用。就是同时开了3个窗口,同时输入了ST03N,并回车。我还在想其他办法,比如开6个窗口多进程循环创建100个物料。
下面的代码实现了,Python多进程的方式去调用SAP GUI。
多进程multiprocessing
在多线程里面使用win32com调用com组件的时候,需要用pythoncom.CoInitialize()初始化一下.
1 import sys 2 import win32com.client 3 import time 4 import pythoncom 5 from multiprocessing import Pool 6 from multiprocessing import freeze_support 7 8 def call_sapgui(sessionID): 9 try: 10 SapGuiAuto = win32com.client.GetObject("SAPGUI") 11 if not type(SapGuiAuto) == win32com.client.CDispatch: 12 return 13 application = SapGuiAuto.GetScriptingEngine 14 if not type(application) == win32com.client.CDispatch: 15 SapGuiAuto = None 16 return 17 connection = application.Children(0) 18 if not type(connection) == win32com.client.CDispatch: 19 application = None 20 SapGuiAuto = None 21 return 22 session = connection.Children(sessionID) 23 if not type(session) == win32com.client.CDispatch: 24 connection = None 25 application = None 26 SapGuiAuto = None 27 return 28 29 session.findById("wnd[0]/tbar[0]/okcd").text = "/nst03n" 30 session.findById("wnd[0]").sendVKey(0) 31 session.findById("wnd[0]/shellcont/shell/shellcont[1]/shell").expandNode("B.999") 32 session.findById("wnd[0]/shellcont/shell/shellcont[1]/shell").topNode = "B" 33 34 except Exception as error_msg: 35 with open("error.txt", "a+") as f: 36 print(error_msg,file=f) 37 finally: 38 session = None 39 connection = None 40 application = None 41 SapGuiAuto = None 42 43 44 def Main(): 45 pythoncom.CoInitialize() 46 po = Pool(3)#开启3个进程池 47 for sessionID in range(3): 48 po.apply_async(call_sapgui,(sessionID,)) 49 po.close() #关闭进程池,关闭后po不再接收新的请求。 50 po.join() #等待po中所有子进程执行完成,必须放在close语句之后。 51 52 if __name__ == "__main__": 53 Main()