想經過Python控制SAP。基於下面的網址實現的。感謝NewJune 提供了頗有用的信息。html
https://www.cnblogs.com/new-june/p/NewJune.html#commentformpython
關於如下代碼,先說結果: 基本沒什麼用。就是同時開了3個窗口,同時輸入了ST03N,並回車。我還在想其餘辦法,好比開6個窗口多進程循環建立100個物料。shell
下面的代碼實現了,Python多進程的方式去調用SAP GUI。session
多進程multiprocessing多線程
在多線程裏面使用win32com調用com組件的時候,須要用pythoncom.CoInitialize()初始化一下.app
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()