首页 > 编程语言 >python调用SAP脚本下载库存报表MB52

python调用SAP脚本下载库存报表MB52

时间:2023-08-24 22:26:00浏览次数:38  
标签:findById wnd python args press session usr MB52 SAP

import math
import os,sys, win32com.client
import clipboard
from pprint import pprint
import csv

        
def get_mb52(session, args = {}, plant = '0001'):
    result = download_from_sap(session, args=args, plant = plant)
    if not result:  #no error from sap download
        full_file_name = save_csv(session, 'mb52')
        print('full_file_name=', full_file_name)
        if full_file_name:        
            result = get_data_from_file(full_file_name)
    return result  

def download_from_sap(session, args={}, plant = '0001'):
    """args {'material':['0789','09980'], 'location':['R023','R024'], 'plant':'0001'}"""
    if not args:
        args = get_plant_args(plant, 'stock_param')        
    
    #plant = args.get('plant')
    location_list = args.get('location')
    material_list = args.get('material')
        
    session.findById("wnd[0]/tbar[0]/okcd").Text = "/nmb52"
    session.findById("wnd[0]").sendVKey(0)
    if session.findById("wnd[0]/sbar").MessageType == "E":
        msg = session.findById("wnd[0]/sbar").Text
        print(msg)
        return msg
        
    field_id = "wnd[0]/usr/btn%_MATNR_%_APP_%-VALU_PUSH"    
    materials = os.linesep.join(material_list) #'\r\n'        
    clipboard.copy(materials)
    session.findById(field_id).press()
    session.findById("wnd[1]/tbar[0]/btn[16]").press()   
    session.findById("wnd[1]/tbar[0]/btn[24]").press()
    session.findById("wnd[1]/tbar[0]/btn[8]").press()

    session.findById("wnd[0]/usr/ctxtWERKS-LOW").Text = "0001" #设置工厂代码
    
    if location_list:
        locations = os.linesep.join(location_list) #'\r\n'        
        clipboard.copy(locations)
        session.findById("wnd[0]/usr/btn%_LGORT_%_APP_%-VALU_PUSH").press()
        session.findById("wnd[1]/tbar[0]/btn[16]").press()   #删除之前的输入
        session.findById("wnd[1]/tbar[0]/btn[24]").press()
        session.findById("wnd[1]/tbar[0]/btn[8]").press()
        
    session.findById("wnd[0]/usr/chkPA_SOND").Selected = True
    session.findById("wnd[0]/usr/ctxtSO_SOBKZ-LOW").Text = "k"
    session.findById("wnd[0]/usr/chkNOZERO").Selected = True
    session.findById("wnd[0]/usr/chkNOVALUES").Selected = True
    session.findById("wnd[0]/usr/chkNEGATIV").Selected = False
    session.findById("wnd[0]/usr/radPA_FLT").Select()
    session.findById("wnd[0]/usr/ctxtP_VARI").Text = "/MB52_xxx"    #设置固定的输出格式layout
    session.findById("wnd[0]/tbar[1]/btn[8]").press()
    
    #there is no data for selection
    if session.ActiveWindow.Name == "wnd[1]":
        msg = session.findById("wnd[1]").PopupDialogText
        print(msg)
        session.findById("wnd[1]").sendVKey(0)
        if msg == "There is no data for the selection":
            return
    
    session.findById("wnd[0]/tbar[1]/btn[45]").press()
    session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").select()
    session.findById("wnd[1]/tbar[0]/btn[0]").press()    
    
def get_data_from_file(file_name):

    field_map = {        
        "Material": "item_code",
        "SLoc": "location",
        "S": "special_stock",
        "Stck no.":"supplier",
        "Unrestricted": "available_qty",
        "Unrestr.": "available_qty",
        "Qual.Insp.": "quality_insp",        
        "BUn": "uom"        
    }
    data = []
    with open(file_name, "r", newline='', encoding='utf-8') as csvfile:
        rows = csv.reader(csvfile, delimiter = '\t')
        for i, row in enumerate(rows):
            if i<3 or not row:
                continue
            if i == 3:
                field_index = {f:get_field_index(row, f) for f in field_map.keys()}
                print('field index', field_index)    
            else:                    
                doc = {}
                for k, v in field_map.items():
                    index = field_index.get(k)
                    if index != -1:
                        doc[v] = row[index]
                for f in ['available_qty','quality_insp']:
                    if doc.get(f):
                        doc[f] = doc[f].replace(',','').replace(" ","")
                        doc[f] = doc[f] and float(doc[f]) or 0        
                data.append(doc) 
    data = [[d.get('item_code'), d.get('location'), d.get('special_stock'), d.get('supplier'),
        d.get('available_qty'), d.get('quality_insp'), d.get('uom')] for d in data]
    pprint('get_data_from_file 2 records %s' % data[:2])
    return data

def save_csv(session, tcode, file_folder=None):
    if file_folder:
        session.findById("wnd[1]/usr/ctxtDY_PATH").text = file_folder 
    else:
        file_folder = session.findById("wnd[1]/usr/ctxtDY_PATH").text
        
    file_name = f"{tcode}_{datetime.datetime.now():%y%m%d_%H%M%S}.csv"
    session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = file_name
    session.findById("wnd[1]/usr/ctxtDY_FILE_ENCODING").text = "4110"   #UTF8 编码,默认0000中文会显示乱码
    session.findById("wnd[1]/tbar[0]/btn[0]").press()
    result = None    
    full_file_name = os.path.join(file_folder, file_name)
    time.sleep(1)    
    for i in range(720):
        if os.path.exists(full_file_name):
            result = full_file_name
            break
        time.sleep(1) 
        
    return result
    
def get_field_index(row, field):
    index = -1
    for i,label in enumerate(row):
        if field == label or (label and field == label.strip()):  #truncate beginning and ending space
            index = i
            break
    if index == -1: print("missing field %s in the layout" % field)
    return index

  

标签:findById,wnd,python,args,press,session,usr,MB52,SAP
From: https://www.cnblogs.com/pythonClub/p/17655293.html

相关文章

  • Python教程:Gzip解压缩
    我们将介绍Python中的gzip解压。我们还将介绍如何使用gzip解压来解压压缩的内容。Python中的Gzip解压在Python中为压缩和解压目的建立了许多库,但我们将介绍Gzip库。它是一个流行的数据压缩工具。我们可以使用gzip,通过对数据进行特殊格式的编码来减少文件的大小,这种格式不......
  • Python SAP 脚本定时自动下载资产清单 S_ALR_87011990
    业务场景使用了外部工作流系统管理固定资产申请,转移(负责人变更),盘点,报废等涉及固定资产的业务,而固定资产采购,折旧等仍在SAP中进行,所以需要定时从SAP中下载包括固定资产账面值的固定资产清单,以作为工作流审批节点流转的依据主要功能说明定时运行自动登录SAP下载SAP固定资......
  • 从SAP GridView中获取数据
    classSapGuiGridView:"""SAP中GridView组件数据的表示对象类。用于从SAP的GridView中读取指定的数据。"""@staticmethoddefget_data(session,_id,columns,handler=None):"""读取查询到的表格数据。......
  • SAP总结
     1.获取session(窗口)SetSapGuiAuto=GetObject("SAPGUI")'GettheSAPGUIScriptingobjectSetSAPApp=SapGuiAuto.GetScriptingEngine'GetthecurrentlyrunningSAPGUISetSAPCon=SAPApp.Children(0)'Getthefirstsystemthatis......
  • 从SAP TableControl中读取数据
    classSapGuiTableControl:"""读取GuiTableControl对象的数据。"""@staticmethoddefget_data(session,_id,columns=None):"""获取指定列的数据,索引从0开始。:paramsession:SAP的GuiSession......
  • Python虚拟环境
    以前在打比赛和做项目的时候都一直都没有注重管理python包,以至于把所有的包都堆到Anaconda下,以前出现包问题的时候能百度解决的解决,结局不了就卸了重装,感觉没什么。最近开始做一些项目,在自己的电脑上做好,去别的地方打包运行,结果要配两次环境非常的麻烦,所以开始认真对待起不同项目......
  • Python 项目以及常见的目录结构
    当今世界,Python可以说是最受欢迎的编程语言之一。作为一种高级动态语言,Python具有简单易学、代码可读性强和生态系统丰富等特点,广泛应用于Web开发、数据科学、机器学习、网络爬虫等领域。在Python项目中,良好的目录结构设计是一个成功项目的关键因素之一。Python项......
  • python 中 if __name__ == '__main__'
    当我们编写Python模块时,有时候需要让某些代码只在该模块作为主程序运行时才执行,而不是被其他模块import引入时就执行。这时候可以使用if__name__=='__main__'这个条件语句。什么是 name 变量在Python中,每个模块(Python文件)都有一个内置变量__name__,用于指示当前模......
  • 使用 conda 管理电脑多个 python 版本
    背景之前一直使用python自带的虚拟环境管理工具(virtualen包),虽然很舒服,可以有不同的软件包环境,但是所有环境都只能基于一个python版本。由于历史原因,系统(Ubuntu)升级时给我新增了一个python3.11,我索性就只保留了这一个版本。这两天要使用open3d,结果发现不支持最新版本的......
  • python独立脚本应用Django项目的环境
    一、需求说明一直用Django在开发一个网站项目,其中的注册用户和登录,都是使用Django自带的认证系统。主要是对密码的加密,在注册或者登录的时候,前端传递多来的密码,我会使用Django的set_password()方法在加密一次经过加密后的数据库中的数据样子如下:......