前几天在网上找了一下 python 连 SAP 的方法,目前有这个开源项目:

1. pysaprfc :   ​​Python SAP RFC module​​​           ​​http://pypi.python.org/pypi/Python%20SAP%20RFC%20module/1.0.0​

2. saprfc/sapnwrfc  : ​​http://www.piersharding.com/blog/​​​  ​​sapnwrfc · PyPI​

首先这项目都需要用到 sap 发布的 连接库文件 librfc.dll ( linux : librfccm.so ) .

librfc.dll 可以在装了sapgui后,在system32 下找到, librfccm.so 可以下载 jco2.x for linux 里面可以找到.

将库文件按系统要求存放在特定库位置, window是system32 下面,linux 是 /usr/lib 下面 

pysaprfc 则可以直接使用了,saprfc 还需要 sap rfc sdk 的.h头件,这个可以在 sap gui 安装包里面找到.

现在的问题是这两种方法都有一个不能处理unicode的字符的问题(从sap里取到的中文都是乱码),似乎需要重新下载新的 sap rfc sdk 或 sap netweaver rfc sdk ,目前我没有权限下载这两个东西,如果有朋友可以下载的,请转一份给我, 另外如果有更好的方法也请不吝赐教...

--------------------------------------------------

2022/03/28 重新看了一下最新的 netweaver sdk ,现在已经有可以用的 sdk了,没有unicode乱码问题。

有sap权限的可以去官网下载​​SAP NetWeaver Remote Function Call (RFC) Software Development Kit (SDK)​​,我这里有在网上找到了windows和linux两个版本的可供大家直接用。

链接: https://pan.baidu.com/s/1wwXgbv2cvjzv_0ki6rAq6Q?pwd=8t5p 提取码: 8t5p

windows使用方法,

1.下载上面windows版本sdk, 并把 "解压目录/nwrfc750P_6-70002755-win\nwrfcsdk\lib " 放入path环境变量中。

2.安装pyrfc模块: pip install pyrfc 

3.测试

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Project: pyrfc_test
# File : test.py
# Author : Long.Xu <fangkailove@yeah.net>
# http://gnolux.blog.csdn.net
# QQ:26564303
# Time : 2022-03-12
# Copyright 2022 Long.Xu All rights Reserved.

from pyrfc import Connection
import re
from pprint import PrettyPrinter

class main():
def __init__(self):
ASHOST='xxx.xxx.xxx.xxx'
CLIENT='888'
SYSNR='00'
USER='userid'
PASSWD='pwd'
self.conn = Connection(ashost=ASHOST, sysnr=SYSNR, client=CLIENT, user=USER, passwd=PASSWD)

def qry(self, Fields, SQLTable, Where = '', MaxRows=50, FromRow=0):
"""A function to query SAP with RFC_READ_TABLE"""

# By default, if you send a blank value for fields, you get all of them
# Therefore, we add a select all option, to better mimic SQL.
if Fields[0] == '*':
Fields = ''
else:
Fields = [{'FIELDNAME':x} for x in Fields] # Notice the format

# the WHERE part of the query is called "options"
options = [{'TEXT': x} for x in Where] # again, notice the format

# we set a maximum number of rows to return, because it's easy to do and
# greatly speeds up testing queries.
rowcount = MaxRows

# Here is the call to SAP's RFC_READ_TABLE
tables = self.conn.call("RFC_READ_TABLE", QUERY_TABLE=SQLTable, DELIMITER='|', FIELDS = Fields, \
OPTIONS=options, ROWCOUNT = MaxRows, ROWSKIPS=FromRow)

# We split out fields and fields_name to hold the data and the column names
fields = []
fields_name = []

data_fields = tables["DATA"] # pull the data part of the result set
data_names = tables["FIELDS"] # pull the field name part of the result set

headers = [x['FIELDNAME'] for x in data_names] # headers extraction
long_fields = len(data_fields) # data extraction
long_names = len(data_names) # full headers extraction if you want it

# now parse the data fields into a list
for line in range(0, long_fields):
fields.append(data_fields[line]["WA"].strip())

# for each line, split the list by the '|' separator
fields = [x.strip().split('|') for x in fields ]

# return the 2D list and the headers
return fields, headers

# Init the class and connect
# I find this can be very slow to do...
s = main()

# Choose your fields and table
fields = ['MATNR','MAKTX']
table = 'MAKT'
# you need to put a where condition in there... could be anything
where = []


# max number of rows to return
maxrows = 10

# starting row to return
fromrow = 0
# Pretty Printer
pp = PrettyPrinter(indent=1)
# query SAP
results, headers = s.qry(fields, table, where, maxrows, fromrow)

print(headers)
pp.pprint(results)
(venv) D:\2.DEVELOP\pyrfc_test>python test.py
['MATNR', 'MAKTX']
[['000000000010103159', 'HCFT110 85/42-15/5黑色(低温)'],
['000000000010103159', 'HCFT110 85/42-15/5 Black'],
['000000000010103160', 'HCFT120 60/30-45/10黑色(低温)'],
['000000000010103160', 'HCFT120 60/30-45/10 Black'],
['000000000010103161', 'HCFT140 160/92-60/20黑色(低温)'],
['000000000010103161', 'HCFT140 160/92-60/20 Black'],
['000000000010103166', '红色防水密封胶 25mm*0.8mm*20m'],
['000000000010103166', 'TAPE65 25mm*0.8mm*20m red'],
['000000000010103167', 'HAT 38/12红色扁'],
['000000000010103167', 'HAT 38/12 red']]

测试没问题。

参考pyrfc文档:​​PyRFC - The Python RFC Connector — pyrfc 2.0.2 documentation​

python 连接SAP的方法 调用 RFC (pyrfc)_linux

增加个调用自定义函数的例子

1。sap bapi如下:

FUNCTION Z_REMOTING_TEST.
*"----------------------------------------------------------------------
*"*"Local interface:
*" IMPORTING
*" VALUE(I_MATNR) TYPE MARA-MATNR
*" EXPORTING
*" VALUE(STR_OUT) TYPE CHAR255
*" TABLES
*" T_MARA STRUCTURE MARA
*"----------------------------------------------------------------------
CONCATENATE '%' I_MATNR '%' into I_MATNR .
select * from mara into table T_mara where matnr like I_MAtnr.
if T_MARA[] is initial .
str_out = '没有记录'.
else .
str_out = '有记录' .
endif.


ENDFUNCTION.

2。python 调用端如下:

def test2():
ASHOST='xxxxxx'
CLIENT='888'
SYSNR='00'
USER='xxx'
PASSWD='xxx'
conn = pyrfc.Connection(ashost=ASHOST, sysnr=SYSNR, client=CLIENT, user=USER, passwd=PASSWD)
# call 方法:第一个参数是 bapi 命, 后面是bapi的参数,注意一定要用 参数名=参数值 的方式
# 返回值 是个列表,会把 export , table 等值都返回, table会以字典列表集的方式返回。
result = conn.call("Z_REMOTING_TEST",I_MATNR='10100001')
print("result:",result['STR_OUT'])
for r in result["T_MARA"]:
print(r["MATNR"])