Git Product home page Git Product logo

pyrfc's Introduction

PyRFC

Asynchronous, non-blocking SAP NetWeaver RFC SDK bindings for Python.

PyPI - Wheel PyPI - Version PyPI - Python Version Ruff PyPI - Downloads REUSE status CII Best Practices

Features

  • Client and Server bindings
  • Automatic conversion between Python and ABAP datatypes
  • Stateless and stateful connections (multiple function calls in the same ABAP session / same context)
  • Sequential and parallel calls, using one or more clients
  • Throughput monitoring

Supported platforms

Requirements

SAP NW RFC SDK 7.50 Patch Level 12

  • see SAP Note 3274546 for a list of bug fixes and enhancements made with this patch release
  • Using the latest version is recommended as SAP NWRFC SDK is fully backwards compatible, from today S4, down to R/3 release 4.6C.
  • Can be downloaded from SAP Software Download Center of the SAP Support Portal, like described at https://support.sap.com/nwrfcsdk.
  • If you are lacking the required authorization for downloading software from the SAP Service Marketplace, please follow the instructions of SAP Note 1037575 for requesting this authorization.

Linux

PyRFC is using source distribution (sdist) installation on Linux systems and Cython is required on Linux system to build the PyRFC package from source. See Installing Cython

Windows

macOS

  • Remote paths must be set in SAP NWRFC SDK for macOS: documentation

  • When the PyRFC is started for the first time, the popups may come-up for each NWRFC SDK library, to confirm the usage. If SAP NW RFC SDK is installed in admin folder, the app shall be first time started with admin privileges, eg. sudo -E

Docker

Download and installation

pip install pyrfc

On Windows and macOS platforms pre-built binary wheel is installed, without local compilation. On Linux platform the package is locally built from source distribution.

Build from source distribution can be requested also on other platforms:

pip install --no-binary pyrfc pyrfc
# or
pip install https://files.pythonhosted.org/packages/.../pyrfc-3.1.0.tar.gz

Alternative build from source installation:

git clone https://github.com/SAP/PyRFC.git
cd PyRFC
# if you use tox
tox -e py311 # for Python 3.11
# or
python -m pip install .
# or
python -m build --wheel --sdist --outdir dist
# or
PYRFC_BUILD_CYTHON=yes python -m build --wheel --sdist --outdir dist
pip install --upgrade --no-index --find-links=dist pyrfc

Run python and type from pyrfc import *. If this finishes silently, without oputput, the installation was successful.

Using virtual environments you can isolate Python/PyRFC projects, working without administrator privileges.

See also the pyrfc documentation, complementing SAP NWRFC SDKdocumentation, especially SAP NWRFC SDK 7.50 Programming Guide.

Getting started

Note: The package must be installed before use.

Call ABAP Function Module from Python

In order to call remote enabled ABAP function module (ABAP RFM), first a connection must be opened.

from pyrfc import Connection
conn = Connection(ashost='10.0.0.1', sysnr='00', client='100', user='me', passwd='secret')

Connection parameters are documented in sapnwrfc.ini file, located in the SAP NWRFC SDK demo folder. Check also section 4.1.2 Using sapnwrfc.ini of SAP NWRFC SDK 7.50 Programming Guide.

Using an open connection, remote function modules (RFM) can be invoked. More info in pyrfc documentation.

# ABAP variables are mapped to Python variables
result = conn.call('STFC_CONNECTION', REQUTEXT=u'Hello SAP!')
print (result)
{u'ECHOTEXT': u'Hello SAP!',
 u'RESPTEXT': u'SAP R/3 Rel. 702   Sysid: ABC   Date: 20121001   Time: 134524   Logon_Data: 100/ME/E'}

# ABAP structures are mapped to Python dictionaries
IMPORTSTRUCT = { "RFCFLOAT": 1.23456789, "RFCCHAR1": "A" }

# ABAP tables are mapped to Python lists, of dictionaries representing ABAP tables' rows
IMPORTTABLE = []

result = conn.call("STFC_STRUCTURE", IMPORTSTRUCT=IMPORTSTRUCT, RFCTABLE=IMPORTTABLE)

print result["ECHOSTRUCT"]
{ "RFCFLOAT": 1.23456789, "RFCCHAR1": "A" ...}

print result["RFCTABLE"]
[{ "RFCFLOAT": 1.23456789, "RFCCHAR1": "A" ...}]

Finally, the connection is closed automatically when the instance is deleted by the garbage collector. As this may take some time, we may either call the close() method explicitly or use the connection as a context manager:

with Connection(user='me', ...) as conn:
    conn.call(...)
# connection automatically closed here

Alternatively, connection parameters can be provided as a dictionary:

def get_connection(conn_params):
    """Get connection"""
    print 'Connecting ...', conn_params['ashost']
    return Connection(**conn_param)

from pyrfc import Connection

abap_system = {
    'user'      : 'me',
    'passwd'    : 'secret',
    'ashost'    : '10.0.0.1',
    'saprouter' : '/H/111.22.33.44/S/3299/W/e5ngxs/H/555.66.777.888/H/',
    'sysnr'     : '00',
    'client'    : '100',
    'trace'     : '3', #optional, in case you want to trace
    'lang'      : 'EN'
}

conn = get_connection(**abap_system)
Connecting ... 10.0.0.1

conn.alive
True

See also pyrfc documentation for Client Scenario

Call Python function from ABAP

# create server for ABAP system ABC
server = Server({"dest": "gateway"}, {"dest": "MME"}, {"port": 8081, "server_log": False})

# expose python function my_stfc_connection as ABAP function STFC_CONNECTION, to be called from ABAP system
server.add_function("STFC_CONNECTION", my_stfc_connection)

# start server
server.start()

# get server attributes
print("Server attributes", server.get_server_attributes())

# stop server
input("Press Enter to stop servers...")

server.stop()
print("Server stoped")

See also pyrfc documentation for Server Scenario and server example source code.

SPJ articles

Highly recommended reading about RFC communication and SAP NW RFC Library, published in the SAP Professional Journal (SPJ)

How to obtain support

If you encounter an issue or have a feature request, you can create a ticket.

Check out the SAP Community (search for "pyrfc") and stackoverflow (use the tag pyrfc), to discuss code-related problems and questions.

Contributing

We appreciate contributions from the community to PyRFC! See CONTRIBUTING.md for more details on our philosophy around extending this module.

Code of Conduct

See Code of Conduct

pyrfc's People

Contributors

amarvin avatar bsrdjan avatar guettli avatar haserver avatar muellma-items avatar n8-i avatar qmacro avatar ryanb58 avatar yashbhutoria avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyrfc's Issues

PyRFC Connection call issues

Hi,

I am trying to get data from SAP system. I tried using below code but unable to return any data. Do I need to pass any thing to connection parameters.

`

from pyrfc import *
conn = Connection(user='XXXXXXXXXX', passwd='XXXXXXXXX', ashost='XXXXXXXXXXXXX', sysnr='XX', client='XXX')
result = conn.call('STFC_CONNECTION', REQUTEXT=u'Hello Sap')
print result
{u'RESPTEXT': u'SAP R/3 Rel. 740 Sysid: CUP Date: 20170405 Time: 190015 Logon_Data: 100/R_NA_L360/E', u'ECHOTEXT': u'Hello Sap'}
result = conn.call('ZBW_TESTC018')
print result
{u'PT_LIST': [], u'PT_COMPANY': []}

`

Is PyRFC the Python equivalent of JCo for Java?

I thought that PyRFC is the same for Python what JCo is for Java. But when I read here

The improvements over the existing classic RFC Library are:
You no longer need to worry about getting the correct structure definitions for your imports, exports and tables. One API call fetches the complete definition of a function module from the backend DDIC and caches it for later use. (Metadata and repository functionality kind of like in JCo.)

especially the part

(Metadata and repository functionality kind of like in JCo.)

I am a bit confused.

Can you clarify, please.

AttributeError: 'str' object has no attribute 'iteritems'

I have below script which is based on clientStfcStructure.py from examples folder:

import os

# Put SAP NW RFC Library on PATH
SAPNWRFC_PATH = os.path.abspath('dependencies/32bit/SAP_NW_RFC_32/lib')
os.environ['PATH'] = SAPNWRFC_PATH + ";" + os.environ['PATH']


from pyrfc import Connection
from pprint import pprint
from configparser import ConfigParser


header = {
    'DOC_TYPE': 'TA',
    'SALES_ORG': '0500',
    'DISTR_CHAN':'01',
    'DIVISION': '01',
    'PURCH_NO_C': 'ABC12345'
}

partners = {
    'PARTN_NUMB': 512345500,
    'NAME': 'Otto GmbH'
}

def main():
    config = ConfigParser()
    config.read('sapnwrfc.cfg')
    params_connection = config._sections['connection']

    conn = Connection(**params_connection)
    result = conn.call('BAPI_SALESORDER_CREATEFROMDAT2', ORDER_HEADER_IN=header, ORDER_PARTNERS=partners)
    pprint(result2)

if __name__ == '__main__':
    main()

Then I run this script (with Python 2.7 32bit) I get the error

AttributeError: 'str' object has no attribute 'iteritems'

If I pass only one keyword-argument to BAPI call like this

result = conn.call('BAPI_SALESORDER_CREATEFROMDAT2', ORDER_HEADER_IN=header)

then it works and I get some answer from BAPI_SALESORDER_CREATEFROMDAT2. Obviously more parameters have to be passed, though because BAPI states

...
u'RETURN': [{u'FIELD': u'',
              u'ID': u'VP',
              u'LOG_MSG_NO': u'000000',
              u'LOG_NO': u'',
              u'MESSAGE': u'Bitte Auftraggeber oder Warenempf\xe4nger eingeben.',
...

Please help with that one. I have spend hours on it but just don't have any more ideas how to further debugg it.

How do I get the PyRFC Egg packages

How do I get the PyRFC Egg packages? Do I have to build the packages myself?

C:\windows\system32>easy_install pyrfc-1.9.3-py2.7-win32
Searching for pyrfc-1.9.3-py2.7-win32
Reading https://pypi.python.org/simple/pyrfc-1.9.3-py2.7-win32/
Couldn't find index page for 'pyrfc-1.9.3-py2.7-win32' (maybe misspelled?)
Scanning index of all packages (this may take a while)
Reading https://pypi.python.org/simple/
No local packages or working download links found for pyrfc-1.9.3-py2.7-win32
error: Could not find suitable distribution for Requirement.parse('pyrfc-1.9.3-py2.7-win32')

Wrong behavior of RAW data type

Hello. I tried to call abap function with RAW import param IM_XSTR and piped export param EX_XSTR.

FUNCTION zsr_mp_datatypes_inout .
  DEFINE mov_fld.
    ex_&1 = im_&1.
  END-OF-DEFINITION.
  ...
  mov_fld xstr.
  ...
  REFRESH et_datatypes.
  APPEND LINES OF it_datatypes TO et_datatypes.
ENDFUNCTION.
from pyrfc import Connection
conn = Connection(...)
response = conn.call('ZSR_MP_DATATYPES_INOUT', IM_XSTR=bytes(range(256)))
request.params['IM_XSTR'] = {bytes} b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x8
response.data['EX_XSTR'] = {bytes} b'\x00\x01\x02\x03\x04\x05\x06\x07\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x

I found that pyrfc got an issue with some bytes like \x08, \x12, \x21 etc.
I check value in SAP remote debugger and it confirm that is pyrfc issue.
sap_gui_debugger

Couldn't find https://pypi.python.org/simple/pyrfc/

I try to install it, but I get the following error:

C:\Python-Projects\SAP>easy_install pyrfc-1.9.4-py3.5-win-amd64.egg
Processing pyrfc-1.9.4-py3.5-win-amd64.egg
removing 'c:\program files (x86)\python35-32\lib\site-packages\pyrfc-1.9.4-py3.5
-win-amd64.egg' (and everything under it)
creating c:\program files (x86)\python35-32\lib\site-packages\pyrfc-1.9.4-py3.5-
win-amd64.egg
Extracting pyrfc-1.9.4-py3.5-win-amd64.egg to c:\program files (x86)\python35-32
\lib\site-packages
pyrfc 1.9.4 is already the active version in easy-install.pth

Installed c:\program files (x86)\python35-32\lib\site-packages\pyrfc-1.9.4-py3.5
-win-amd64.egg
Processing dependencies for pyrfc==1.9.4
Searching for pyrfc==1.9.4
Reading https://pypi.python.org/simple/pyrfc/
Couldn't find index page for 'pyrfc' (maybe misspelled?)
Scanning index of all packages (this may take a while)
Reading https://pypi.python.org/simple/
No local packages or download links found for pyrfc==1.9.4
error: Could not find suitable distribution for Requirement.parse('pyrfc==1.9.4'
)

Empty values in TIME fields

Some SAP standard BAPIs return an 'empty' rather than 'initial' value in a time field. For example, BAPI_BUS1240_GETDETAIL can cause Python dumps.

I have produced a repeatable scenario for the problem without having to use BAPI_BUS1240_GETDETAIL, example follows below:

Test program - python

!/usr/bin/env /usr/bin/python

from pyrfc import Connection, ABAPApplicationError, ABAPRuntimeError, LogonError, CommunicationError
from ConfigParser import ConfigParser
from pprint import PrettyPrinter

def main():

try:

    config = ConfigParser()
    config.read('sapnwrfc.cfg')
    params_connection = config._sections['connection']
    conn = Connection(**params_connection)

    result = conn.call('ZNWRFC_TIMESTAMP')

    pp = PrettyPrinter(indent=4)
    pp.pprint(result)

except CommunicationError:
    print u"Could not connect to server."
    raise
except LogonError:
    print u"Could not log in. Wrong credentials?"
    raise
except (ABAPApplicationError, ABAPRuntimeError):
    print u"An error occurred."
    raise

if name == 'main':
main()

Test function - ABAP

function znwrfc_timestamp.
"----------------------------------------------------------------------
*"
"Local Interface:
*" EXPORTING
*" VALUE(EV_TIME) TYPE SYUZEIT
*"----------------------------------------------------------------------

  • This will make pyrfc dump
    ev_time = ''.
  • Uncomment this out and it will correctly initialize the field and it doesn't dump
    *clear ev_time.

endfunction.

Example of dump

$ python timedump.py
Traceback (most recent call last):
File "timedump.py", line 31, in
main()
File "timedump.py", line 15, in main
result = conn.call('ZNWRFC_TIMESTAMP')
File "_pyrfc.pyx", line 368, in pyrfc._pyrfc.Connection.call (pyrfc/_pyrfc.c:4006)
File "_pyrfc.pyx", line 1837, in pyrfc._pyrfc.wrapResult (pyrfc/_pyrfc.c:19400)
File "_pyrfc.pyx", line 2013, in pyrfc._pyrfc.wrapVariable (pyrfc/_pyrfc.c:21282)
File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data ' 00000' does not match format '%H%M%S'

Version

pyrfc-1.9.4-py2.7-linux-x86_64.egg

Error while setting up PyRFC

I'm having a problem setting up PyRFC on debian.
On a clean install I've installed python 3.5 and put the nwrfcsdk to /usr/sap/lib as in the install documentation. ldconfig is reporting no problems.
I've installed PyRFC using easy-install.

When trying to create a connection in python, I'm getting the following error:
Traceback (most recent call last): File "/code/sap.py", line 6, in <module> from pyrfc import Connection File "/usr/local/lib/python3.5/site-packages/pyrfc-1.9.5-py3.5-linux-x86_64.egg/pyrfc/__init__.py", line 22, in <module> from pyrfc._pyrfc import get_nwrfclib_version, Connection, TypeDescription, FunctionDescription, Server ImportError: /usr/local/lib/python3.5/site-packages/pyrfc-1.9.5-py3.5-linux-x86_64.egg/pyrfc/_pyrfc.cpython-35m-x86_64-linux-gnu.so: undefined symbol: PyFPE_jbuf
Do you have an idea what's wrong with PyFPE_jbuf?

NiHLGetNodeAddr: hostname cached as unknown, although it is the server's public domain name

Hello.

First and foremost, kudos to the people who is developing this wrapper for the great work they are doing.

I think I am facing a pretty strange error while trying to connect to a SAP server. However, I am a pretty newbie to RFC. I am trying to connect from an Ubuntu 14.04 LTS server (pyrfc-1.9.5-py2.7-linux-x86_64 and SAP NW RFC SDK 7.20) to SAP through a SAPRouter, but this is the exception PyRFC keeps raising:

>>> conn = Connection(**conn_params)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "src/pyrfc/_pyrfc.pyx", line 164, in pyrfc._pyrfc.Connection.__init__ (src/pyrfc/_pyrfc.c:2685)
  File "src/pyrfc/_pyrfc.pyx", line 202, in pyrfc._pyrfc.Connection._open (src/pyrfc/_pyrfc.c:3312)
  File "src/pyrfc/_pyrfc.pyx", line 232, in pyrfc._pyrfc.Connection._error (src/pyrfc/_pyrfc.c:3532)
CommunicationError: RFC_COMMUNICATION_FAILURE (rc=1): key=RFC_COMMUNICATION_FAILURE, message=
LOCATION    CPIC (TCP/IP) on local host with Unicode
ERROR       hostname '<My server's public domain name>' unknown
TIME        Fri Mar 31 06:04:02 2017
RELEASE     721
COMPONENT   NI (network interface)
VERSION     40
RC          -2
MODULE      nixxhl.cpp
LINE        193
DETAIL      NiHLGetNodeAddr: hostname cached as unknown
COUNTER     4
 [MSG: class=, type=, number=, v1-4:=;;;]

It seems like the error is being produced by my server itself because it isn't able to solve its own name. This is weird, because the domain name is public and it can be solved from the shell without problems.

Thanks!

How to connect server with load balancing mode?

  File "src\pyrfc\_pyrfc.pyx", line 164, in pyrfc._pyrfc.Connection.__init__ (src/pyrfc\_pyrfc.c:2685)
  File "src\pyrfc\_pyrfc.pyx", line 202, in pyrfc._pyrfc.Connection._open (src/pyrfc\_pyrfc.c:3312)
  File "src\pyrfc\_pyrfc.pyx", line 232, in pyrfc._pyrfc.Connection._error (src/pyrfc\_pyrfc.c:3532)
pyrfc._exception.CommunicationError: RFC_COMMUNICATION_FAILURE (rc=1): key=RFC_COMMUNICATION_FAILURE, message=
ERROR       service '10.5.100.12' unknown
TIME        Fri Mar 03 16:54:55 2017
RELEASE     721
COMPONENT   NI (network interface)
VERSION     40
RC          -3
MODULE      ninti.c
LINE        933
DETAIL      NiPGetServByName: '10.5.100.12' not found
SYSTEM CALL getaddrinfo
COUNTER     1
 [MSG: class=, type=, number=, v1-4:=;;;]

How to establish a client connection to application server utilizing sapnwrfc.ini?

Just can't figure it out from documentation how to do it. The docs say pyrfc by default looks for sapnwrfc.ini in current folder. Let's asume I have this content in my sapnwrfc.ini

DEST=???
R3NAME=DE999
ASHOST=ABC123
SYSNR=01
CLIENT=123
USER=username
PASSWD=password
LANG=DE
TRACE=3
  1. What is DEST?
  2. How to call Connection()?
> from pyrfc import Connection
> my_sap = Connection()
> Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "pyrfc\_pyrfc.pyx", line 150, in pyrfc._pyrfc.Connection.__init__ (pyrfc\_pyrfc.c:2281)
    File "pyrfc\_pyrfc.pyx", line 188, in pyrfc._pyrfc.Connection._open (pyrfc\_pyrfc.c:2927)
    File "pyrfc\_pyrfc.pyx", line 218, in pyrfc._pyrfc.Connection._error (pyrfc\_pyrfc.c:3153)
    pyrfc._exception.ExternalRuntimeError: RFC_INVALID_PARAMETER (rc=20): key=RFC_INVALID_PARAMETER, message=Invalid parameter 'unsigned paramCount' was passed to the API call [MSG: class=, type=, number=, v1-4:=;;;]
    ```

pyrfc._exception.ExternalRuntimeError: RFC_BUFFER_TOO_SMALL (rc=23)

File "_pyrfc.pyx", line 368, in pyrfc._pyrfc.Connection.call (pyrfc_pyrfc.c:4006)
File "_pyrfc.pyx", line 1837, in pyrfc._pyrfc.wrapResult (pyrfc_pyrfc.c:19400)
File "_pyrfc.pyx", line 1910, in pyrfc._pyrfc.wrapVariable (pyrfc_pyrfc.c:19954)
File "_pyrfc.pyx", line 1882, in pyrfc._pyrfc.wrapTable (pyrfc_pyrfc.c:19732)
File "_pyrfc.pyx", line 1855, in pyrfc._pyrfc.wrapStructure (pyrfc_pyrfc.c:19609)
File "_pyrfc.pyx", line 1917, in pyrfc._pyrfc.wrapVariable (pyrfc_pyrfc.c:20034)
File "_pyrfc.pyx", line 2046, in pyrfc._pyrfc.wrapString (pyrfc_pyrfc.c:21820)
pyrfc._exception.ExternalRuntimeError: RFC_BUFFER_TOO_SMALL (rc=23): key=RFC_BUFFER_TOO_SMALL, message= [MSG: class=, type=, number=, v1-4:=;;;]

It's 1st time to us to use this lib to communicate with sap. Hope that we can explain how it can be reproduced -

  1. a sap char field with length 8. If this field filled with >4 Chinese characters
  2. in the rfc code, we also specify this field length to 8

The error will happen.

Temp fix: in the rfc code, specify the length to sap_char_field_length * 2 + 1

Install error: Could not find suitable distribution for Requirement.parse('pyrfc==1.9.5')

I'm trying to install pyrfc on my system : pyrfc-1.9.5-py3.5-win-amd64.egg

OS : Windows 7 64 bits
Python : Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32

I'm trying to install with :
.\easy_install.py https://github.com/SAP/PyRFC/raw/master/dist/pyrfc-1.9.5-py3.5-win-amd64.egg
(also tried with locally downloaded egg file which gives same error)

I have the following message :
Installed c:\users\ulhe0002\appdata\local\programs\python\python36\lib\site-packages\pyrfc-1.9.5-py3.5-win-amd64.egg
Processing dependencies for pyrfc==1.9.5
Searching for pyrfc==1.9.5
Reading https://pypi.python.org/simple/pyrfc/
Couldn't find index page for 'pyrfc' (maybe misspelled?)
Scanning index of all packages (this may take a while)
Reading https://pypi.python.org/simple/
No local packages or working download links found for pyrfc==1.9.5
error: Could not find suitable distribution for Requirement.parse('pyrfc==1.9.5')

DLL load failed: %1 is not a valid Win32 application.

My problem:
I am trying to contact SAP with python using the PYRFC on windows.
I am using Python3.4 AMD 64 - win 64, and I have followed these instructions web pages. this
and this also
but after I have finished all instructions, I tried to import PYRFC in python, but I got this issue.
My Issue:

ImportError: DLL load failed: %1 is not a valid Win32 application.

(Windows) This error occurs when SAP NW RFC Library 64bit version is installed on a system with 32bit version Python.

I don't know why I got this issues as I am running on a 64bit version python and 64bit version SAP NW RFC Library.
So, Is the problem that I am using python3.4 and this mean I have to use python2.7 or should I change my version to 32bit version instead of 64 ?

ImportError: cannot import name 'Connection'

Hi Guys,
Sorry if this is obvious question. I am new to python, exploring the python/SAP workings.
I have followed the documentation steps. Unfortunately, I am getting "cannot import name Connection" error. It looks like basic error but no clue where I need to check. Could you please help.

Regards,
Gopi

[S]upport - setup connection

Hi all,

I'm trying to setup a connection through load balancer using saprouter string.
I'm not sure how to format it all, hopefully someone can/will help me out here.

from pyrfc import Connection

TEST = {
    'user'      : 'myUser',
    'passwd'    : 'myPass',
    'saprouter' : '/H/198.125.208.20/S/3299/H/',
    'mshost'    : 'SV006P0G',
    'sysid'     : '68',
    'group'     : '840_SAPGUI',
    'client'    : '840',
    'trace'     : '3',
    'lang'      : 'EN'
}

conn = get_connection(TEST)
#want to do a check here
conn.close()

Parts of the details are provided by external party who supports our SAP system.
The response I get is:

Traceback (most recent call last):
  File "asd.py", line 2, in <module>
    conn = Connection(user='myUser', passwd='myPass', saprouter='/H/198.125.208.20/S/3299/H/', mshost='SV006P0G', sysnr='68', client='840')
  File "_pyrfc.pyx", line 123, in pyrfc._pyrfc.Connection.__init__ (pyrfc/_pyrfc.c:2110)
  File "_pyrfc.pyx", line 161, in pyrfc._pyrfc.Connection._open (pyrfc/_pyrfc.c:2613)
  File "_pyrfc.pyx", line 191, in pyrfc._pyrfc.Connection._error (pyrfc/_pyrfc.c:2792)
pyrfc._exception.CommunicationError: RFC_COMMUNICATION_FAILURE (rc=1): key=RFC_COMMUNICATION_FAILURE, message= [MSG: class=, type=, number=, v1-4:=;;;]

This shouldn't be such a rocket science... should it?
Can someone point me out whats going wrong here

fill_and_submit_unit / confirm_unit return values

We have modified the clientIDoc example, to call IDOC_INBOUND_SINGLE - now we would like to get the SAP return value, which should contain the IDoc number.

However, fill_and_submit_unit only returns the unit dictionary (containing the ID, as well as background and queue setting) - and confirm_unit does not return anything (None).

Questions:

  1. Is there a way to get the actual SAP return value?

  2. Is the unit ID used (and stored) somewhere on the SAP server side, so that we could maybe find a relation from the unit ID to the actual transaction?

  3. Is there any advantage in using this unit approach, compared to making a direct RFC call to IDOC_INBOUND_SINGLE / IDOC_INBOUND_SYNCHRONOUS / IDOC_INBOUND_ASYNCHRONOUS?

Enable Background RFC Requests

Currently bgrfc is marked as not operational. Enabling the use of background processing is essential for large result sets due to RFC timeout issues. Not trying to be selfish but the immediate need is for enabling this functionality in the client, not on the server.

Three key aspects seem to be important in this process:

  1. Triggering the execution of a background RFC on an external system
  2. Monitoring the execution of the background process to determine status and completion
  3. Retrieving the results of the background process once the request is complete

Question: Is it possible to call a SAP transaction?

Is it possible to call a transaction like in SAP GUI e.g. VA01?

Or is a transaction like e.g. VA01 just processed by some BAPI behind the scenes of SAP GUI? If so - how to find out which BAPI(s) a transaction refers to?

No module named 'ConfigParser'

I tried to run clientStfcStructure.py (with Python 3.5.2 - 64bit) which resulted in:

Traceback (most recent call last):
  File "clientStfcStructure.py", line 5, in <module>
    from ConfigParser import ConfigParser
ImportError: No module named 'ConfigParser'

Then I install "ConfigParser" with pip install ConfigParser which gave me configparser (3.5.0). Then I tried to run clientStfcStructure.py again getting the same error as above.

After renaming from ConfigParser to from configparser in line 5 of clientStfcStructure.py I get next error:

Traceback (most recent call last):
  File "clientStfcStructure.py", line 35, in <module>
    main()
  File "clientStfcStructure.py", line 31, in main
    result = conn.call('STFC_STRUCTURE', IMPORTSTRUCT=imp)
  File "pyrfc\_pyrfc.pyx", line 359, in pyrfc._pyrfc.Connection.call (pyrfc\_pyrfc.c:4065)
  File "pyrfc\_pyrfc.pyx", line 1531, in pyrfc._pyrfc.fillFunctionParameter (pyrfc\_pyrfc.c:17862)
  File "pyrfc\_pyrfc.pyx", line 1632, in pyrfc._pyrfc.fillVariable (pyrfc\_pyrfc.c:19179)
  File "pyrfc\_pyrfc.pyx", line 1568, in pyrfc._pyrfc.fillVariable (pyrfc\_pyrfc.c:18346)
  File "pyrfc\_pyrfc.pyx", line 1543, in pyrfc._pyrfc.fillStructureField (pyrfc\_pyrfc.c:17977)
  File "pyrfc\_pyrfc.pyx", line 1632, in pyrfc._pyrfc.fillVariable (pyrfc\_pyrfc.c:19179)
  File "pyrfc\_pyrfc.pyx", line 1579, in pyrfc._pyrfc.fillVariable (pyrfc\_pyrfc.c:18493)
  File "pyrfc\_pyrfc.pyx", line 1639, in pyrfc._pyrfc.fillBytes (pyrfc\_pyrfc.c:19306)
TypeError: ('expected bytes, str found', 'RFCHEX3', 'IMPORTSTRUCT')

Unable to connect to SAP from AWS Lambda

Hi All,

I am trying to connect our SAP system from AWS Lambda. I am getting the following error
FC_COMMUNICATION_FAILURE (rc=1): key=RFC_COMMUNICATION_FAILURE, message= LOCATION CPIC (TCP/IP) on local host with Unicode ERROR hostname 'ip-10-34-143-151' unknown TIME Fri Sep 15 21:24:28 2017 RELEASE 721 COMPONENT NI (network interface) VERSION 40 RC -2 MODULE nixxhl.cpp LINE 193 DETAIL NiHLGetNodeAddr: hostname cached as unknown COUNTER 2 [MSG: class=, type=, number=, v1-4:=;;;] RFC_COMMUNICATION_FAILURE (rc=1): key=RFC_COMMUNICATION_FAILURE, message= LOCATION CPIC (TCP/IP) on local host with Unicode ERROR hostname 'ip-10-34-143-151' unknown TIME Fri Sep 15 21:24:28 2017 RELEASE 721 COMPONENT NI (network interface) VERSION 40 RC -2 MODULE nixxhl.cpp LINE 193 DETAIL NiHLGetNodeAddr: hostname cached as unknown COUNTER 2 [MSG: class=, type=, number=, v1-4:=;;;]: CommunicationError
the call stack shows
File "src/pyrfc/_pyrfc.pyx", line 164, in pyrfc._pyrfc.Connection.__init__ File "src/pyrfc/_pyrfc.pyx", line 208, in pyrfc._pyrfc.Connection._open File "src/pyrfc/_pyrfc.pyx", line 238, in pyrfc._pyrfc.Connection._error pyrfc._exception.CommunicationError: RFC_COMMUNICATION_FAILURE (rc=1):
ip-10-34-143-151 is the hostname that AWS gives to the instance which is running the lambda function

my sapcfg looks like
mshost=146.215.xxx.xx
msserv=3611

Any help would be appreciated

UnicodeDecodeError: 'utf8' codec can't decode byte 0xc2

I am developing a query for the HRP1000 table using RFC_READ_TABLE. The code is below. I have used this same code for a number of other tables with no issue. I am querying for the Position Codes and Position Descriptions in HRP1000.

I get the error below before getting all of the rows in the table that satisfy the query. The error is happening during the call for the RFC_READ_TABLE by PyRFC.

I am not sure if there is anything I could do to trap this error. Any suggestion would be appreciated. I am thinking that the fix is going to require some modification to PyRFC. I tried using the unicodecsv module for python but that will not help I think.

Let me mention that though the code that I have included here is in development it works really well to get data extracts from SAP and written to a csv file and could be pretty easily changed for other formats of files and includes using all or almost all of the parameters and options for RFC_READ_TABLE.

============= Error ===================================
Traceback (most recent call last):
File "I:\Apps\PyRFC-master\examples\sap-hrp1000-p.py", line 167, in
main()
File "I:\Apps\PyRFC-master\examples\sap-hrp1000-p.py", line 65, in main
tables = conn.call('RFC_READ_TABLE', QUERY_TABLE=table, OPTIONS = options, DELIMITER='|', FIELDS = fields2, ROWSKIPS = rowskips,ROWCOUNT = ROWS_AT_A_TIME)
File "_pyrfc.pyx", line 368, in pyrfc._pyrfc.Connection.call (pyrfc_pyrfc.c:4006)
File "_pyrfc.pyx", line 1837, in pyrfc._pyrfc.wrapResult (pyrfc_pyrfc.c:19400)
File "_pyrfc.pyx", line 1910, in pyrfc._pyrfc.wrapVariable (pyrfc_pyrfc.c:19954)
File "_pyrfc.pyx", line 1882, in pyrfc._pyrfc.wrapTable (pyrfc_pyrfc.c:19732)
File "_pyrfc.pyx", line 1855, in pyrfc._pyrfc.wrapStructure (pyrfc_pyrfc.c:19609)
File "_pyrfc.pyx", line 1917, in pyrfc._pyrfc.wrapVariable (pyrfc_pyrfc.c:20034)
File "_pyrfc.pyx", line 2049, in pyrfc._pyrfc.wrapString (pyrfc_pyrfc.c:21861)
File "\ms240xxxx.na.xxxxxx.net\ctxredir$\mdufXXXX\Apps\python2.7.8\lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xc2 in position 46: unexpected end of data

========================== End of Error ===================

================== Code ================================

from pyrfc import Connection, ABAPApplicationError, LogonError
from datetime import date
from ConfigParser import ConfigParser
import unicodecsv

conn = ""

NOW = date.today() # get today's date
DATESTR = NOW.strftime("%m_%d_%Y") # Assign formatted date to variable
FILENAME = ("HRP000_Position_snapshot_" + DATESTR + ".csv")

f = open(FILENAME,'w')

def main():
try:
config = ConfigParser()
config.read('sapnwrfc.cfg')
#params_connection = config._sections['connection']
params_connection = config._sections['pe1']

params_connection["user"] = user

params_connection["passwd"] = passwd

    conn = Connection(**params_connection)
except LogonError:
    print "Invalid username or password"

fields = []
fields_name = []
counter = 0
table="HRP1000"
#print table

#fields2 =[{'FIELDNAME':'PLVAR'}, {'FIELDNAME':'OTYPE'}, {'FIELDNAME':'OBJID'}, {'FIELDNAME':'BEGDA'}, {'FIELDNAME':'ENDDA'}, {'FIELDNAME':'OTJID'}, {'FIELDNAME':'SHORT'},{'FIELDNAME':'STEXT'}]
fields2 =[{'FIELDNAME':'OBJID'}, {'FIELDNAME':'BEGDA'}, {'FIELDNAME':'ENDDA'},{'FIELDNAME':'STEXT'}]


options = [{ 'TEXT': "PLVAR = '01' AND OTYPE = 'S' AND ENDDA = '99991231'"}]


ROWS_AT_A_TIME = 100
rowskips = 0
count = 0
while True:
    #print rowskips
    data_fields = []
    data_names = []
    #tables = conn.call('RFC_READ_TABLE', OPTIONS = options, FIELDS = fields2, QUERY_TABLE=table, DELIMITER='|', ROWSKIPS = rowskips,ROWCOUNT = ROWS_AT_A_TIME)
    #tables = conn.call("RFC_READ_TABLE", OPTIONS = options, QUERY_TABLE= table, DELIMITER='|')
    print "ok before tables"
    tables = conn.call('RFC_READ_TABLE', QUERY_TABLE=table, OPTIONS = options, DELIMITER='|', FIELDS = fields2, ROWSKIPS = rowskips,ROWCOUNT = ROWS_AT_A_TIME)

    print tables

    print "ok after tables"
    data_fields = tables["DATA"]
    data_names = tables["FIELDS"]
    #data_fields = data_fields.encode("utf-8")

print data_fields

print ""

print ""

print ""

print data_names

print ""

print ""

print ""

    long_fields = len(data_fields)
    long_names = len(data_names)

    rowskips = rowskips + ROWS_AT_A_TIME

    #print rowskips
    fields = []
    field_name = []

    for line in range(0, long_fields):
        #fields.append(unicodecsv.reader(data_fields[line]["WA"].strip(), encoding='utf-8'))
        #fields = (unicodecsv.writer(fields, encoding='utf-8')

        fields.append(data_fields[line]["WA"].strip())
    #print fields
    #print ""
    #print ""

    for line in range(0, long_names):
        fields_name.append(data_names[line]["FIELDNAME"].strip())

    #print fields_name
    #print ""
    #print ""
    #print ""

    output=""    

    for line in range(0, long_names):
        field_name = fields_name[line]
        output = output + field_name + ","
    output = output.rstrip(",")
    output = output + "\n"
    if count == 0:
        print output
        f.write(str(output))
        count = 1
    output = ""

    for line in range(0, long_fields):
        data_split = fields[line].split("|")

        for line in range(0, long_names):
            #print data_split[line]
            #print " before data_split ok"

            output = output + data_split[line].encode("utf-8") + ","
            #print "after data_split ok" 
            #output = unicodecsv.reader(line, encoding='utf-8') 
            #output = output + data_split[line].encode("utf-8") + ","
            #output = output + data_split[line] + ","
            #r = unicodecsv.reader(f, encoding='utf-8')
        output = output.rstrip(",")
        output = output + "\n"
    print output
    print "output ok before write"
    f.write(str(output))
    print "output ok after write"
    output = ""

    if len(tables['DATA']) < ROWS_AT_A_TIME:
        break
conn.close()

f.close()      

f2 = open(FILENAME,'r+')
for line in f2:
if line.strip():
f2.write(line)

#except ABAPApplicationError:
#    output = "Table %s was not found" % table

output = "

Table %s was not found

" % table

#    return output

##return output

f2.close()

if name == 'main':
main()

Structure of FM parameters is cached

Hello.
I've got functional module ZHHDEMO_STRUCT_MOD with EX_ZHHT_COL2 param.

FUNCTION ZHHDEMO_STRUCT_MOD.
*"----------------------------------------------------------------------
*"*"Local Interface:
*"  EXPORTING
*"     VALUE(EX_ZHHT_COL2) TYPE  ZHHTT_COL2
*"----------------------------------------------------------------------

  DATA: ls_col2 TYPE zhhs_col2.

  ls_col2-COL1 = 'col1_1'.
  ls_col2-COL2 = 'col2_1'.

  APPEND ls_col2 TO EX_ZHHT_COL2.

  ls_col2-COL1 = 'col1_2'.
  ls_col2-COL2 = 'col2_2'.

  APPEND ls_col2 TO EX_ZHHT_COL2.

ENDFUNCTION.

selection_004

And I've got python script that performs the following sequence of actions:

  1. Prints structure of EX_ZHHT_COL2 parameter;
  2. Prints function result ZHHDEMO_STRUCT_MOD;
  3. Gives me the time to modify structure of EX_ZHHT_COL2 parameter;
  4. Prints structure of EX_ZHHT_COL2 param again. This is proof that the structure has been changed;
  5. Prints function result ZHHDEMO_STRUCT_MOD which exactly the same as pt 2.
import pyrfc

connection_info = {
    # some connection data here
}

function_name = u'ZHHDEMO_STRUCT_MOD'
table_name = u'ZHHTT_COL2'


def get_structure():
    with pyrfc.Connection(**connection_info) as con:
        interface_response = con.call(
            'RFC_GET_FUNCTION_INTERFACE',
            **{'FUNCNAME': function_name}
        )
        assert any(p[u'TABNAME'] == table_name for p in interface_response[u'PARAMS'])
        structure_response = con.call(
            'RFC_GET_STRUCTURE_DEFINITION',
            **{'TABNAME': table_name}
        )
        fields = structure_response[u'FIELDS']
        return [f[u'FIELDNAME'] for f in fields]


def function_call():
    with pyrfc.Connection(**connection_info) as con:
        return con.call(function_name)


if __name__ == '__main__':
    print('STRUCTURE 1', get_structure())
    print('RESULT 1', function_call())
    raw_input('Structure changed now. Press Enter to continue...')
    print('STRUCTURE 2', get_structure())
    print('RESULT 2', function_call())

I change the structure as follows:
selection_006

selection_005

Python script gives me output:

('STRUCTURE 1', [u'ZHHS_COL2', u'COL1', u'COL2'])
('RESULT 1', {u'EX_ZHHT_COL2': [{u'COL2': u'col2_1', u'COL1': u'col1_1'}, {u'COL2': u'col2_2', u'COL1': u'col1_2'}]})
Structure changed now. Press Enter to continue...
('STRUCTURE 2', [u'ZHHS_COL2', u'COL1', u'COL2', u'COL3'])
('RESULT 2', {u'EX_ZHHT_COL2': [{u'COL2': u'col2_1', u'COL1': u'col1_1'}, {u'COL2': u'col2_2', u'COL1': u'col1_2'}]})

The next launch gives me the right output:

('STRUCTURE 1', [u'ZHHS_COL2', u'COL1', u'COL2', u'COL3'])
('RESULT 1', {u'EX_ZHHT_COL2': [{u'COL2': u'col2_1', u'COL3': u'', u'COL1': u'col1_1'}, {u'COL2': u'col2_2', u'COL3': u'', u'COL1': u'col1_2'}]})
Structure changed now. Press Enter to continue...
('STRUCTURE 2', [u'ZHHS_COL2', u'COL1', u'COL2', u'COL3'])
('RESULT 2', {u'EX_ZHHT_COL2': [{u'COL2': u'col2_1', u'COL3': u'', u'COL1': u'col1_1'}, {u'COL2': u'col2_2', u'COL3': u'', u'COL1': u'col1_2'}]})

Transmission too slow

Hi Gurus,

I use the PyRFC to pull workload data from SAP, it works fine.
However, when the SAP system is too big, it takes nearly half an hour to transfer.
Any way to optimize the below statement?

result = conn.call('SWNC_COLLECTOR_GET_AGGREGATES',
COMPONENT=u'TOTAL',
ASSIGNDSYS= self.sysname,
PERIODTYPE=u'M', ##monthly
PERIODSTRT=datetime.date(year,month,01),
SUMMARY_ONLY=u'')

Thank you very much!

BR
Loewe Chiu

How to deal with BAPIs that internally call transactions?

From PyRFC point of view how to deal with BAPIs that internally call transactions?

For example BAPI_BILLINGDOC_CREATE (TCODE: VF01) - calling it result in a runtime error (Der Laufzeitfehler DYNPRO_SEND_IN_BACKGROUND ist aufgetreten)

# Importing SAP module from `SAP.py` below
>>> from SAP import SAP
>>> dest_01 = SAP('DE9')
>>> dest_01.call_bapi('BAPI_BILLINGDOC_CREATE')
Result: {u'RETURN': [{u'TYPE': u'A', u'MESSAGE_V2': u'', u'NUMBER': u'341', u'MESSAGE_V1': u'DYNPRO_SEND_IN_BACKGROUND', u'LOG_NO': u'', u'MESSAGE_V3': u'', u'MESSAGE_V4': u'', u'MESSAGE': u'Der Laufzeitfehler DYNPRO_SEND_IN_BACKGROUND ist aufgetreten', u'LOG_MSG_NO': u'000000', u'ID': u'00'}]}
{u'RETURN': [{u'TYPE': u'A', u'MESSAGE_V2': u'', u'NUMBER': u'341', u'MESSAGE_V1': u'DYNPRO_SEND_IN_BACKGROUND', u'LOG_NO': u'', u'MESSAGE_V3': u'', u'MESSAGE_V4': u'', u'MESSAGE': u'Der Laufzeitfehler DYNPRO_SEND_IN_BACKGROUND ist aufgetreten', u'LOG_MSG_NO': u'000000', u'ID': u'00'}]} >>>

SAP.py module:

# -*- coding: utf-8 -*-

import os
SAPNWRFC_PATH = os.path.abspath('dependencies/32bit/SAP_NW_RFC_32/lib')
os.environ['PATH'] = SAPNWRFC_PATH + ";" + os.environ['PATH']

import pyrfc
import datetime

class SAP():
  def __init__(self, sap_destination):
    self.sap = pyrfc.Connection(DEST=sap_destination)

  def call_bapi(self, bapi, **kwargs):
        try:
            result = self.sap.call(bapi, **kwargs)
            return result
        except AttributeError as error:
            raise (error)

RFCTable with TBL1024 structure

Hello

To upload a PDF binary file to SAP I can use an RFC function module. This FM requires two specific parameters:

  • IC_ARC_OBJECT = the document class to define the mime type in SAP (OAC2)
  • IN_CONTENT_LENGHT = IMPORTING data type, is the size of the file
  • IT_CONTENT = IMPORTING table of structure TBL1024, table with the bytes of the file, cut into pieces of size 1024
  • ET_MESSAGES = just a BAPIRET2 table to check on errors (RETURN table)

The function module is successfully executed in the PyThon program but when I break on the function module to check on the content of IT_CONTENT I can see that the lines of the table is not filled in correctly:

Extraction of the python program call of the FM:
arc_object = "ZZ_PDF" content = Arc.get_arc_content(filename) size = Arc.get_size(filename) messages = [] result = connection.call("ZZ_UPLOAD_FILE", IC_ARC_OBJECT= arc_object, IN_CONTENT_LENGTH= str(size), IT_CONTENT= content, ET_MESSAGES= messages ) messages = result['ET_MESSAGES'] for mes in messages: print mes['MESSAGE']

Extraction of the python function Arc.get_arc_content(filename)
`

def get_arc_content(filename="file.pdf"):
maxLineLength = 1024
structure = []
if filename == '':
filename = 'file.pdf'
with open(filename, 'rb') as file1:
f = file1.read()
n = 1024
fl = [f[i:i + n] for i in range(0, len(f), n)]

content = []
for line in fl:
    lineapp = {
        u"LINE": line
    }
    print len(line)
    content.append(lineapp)

return content

`

The result in SAP is the following for the parameters:

  • IN_CONTENT_LENGHT = 000000007945 (7.8 kb)

  • IT_CONTENT = 8 x 1 lines: (4lines)
    LINE1 255044462D312E3300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
    LINE2 B89B067867673EAB00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
    LINE3 5BF4CB23B9A7513700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
    LINE4 61DB44B3B0AAB12500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
    ....
    LINE8
    202020202020202000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

The expecting result for IT_CONTENT, checked with FM ARCHIVE_OBJECT_GET, should be something like:
LINE1
255044462D312E330D0A25E2E3CFD30D0A25525354585044463320506172616D65746572733A204452535458680D0A322030206F626A0D0A3C3C0D0A2F46696C7465722033203020520D0A2F4C656E67
LINE2
FA1D555450C8EF41AC263F14BC03C49BDD773CF22BC43FD21B3565DA2DFCCB83D8FFAC7BCBBBEBE6DED0AD68DEA29B349398511824DDDCFFAF41EA7FDADDF67EE61EF3FC303293F7E96351A911F8DE10
LINE3
FB4A559526CD6AED428976E80F8DD0B02517C4178D1EFB73C65792D09CFE5C717883BE38E61ED0AB3ADC0983C103E4338A1B210DA086DA73375E679C0A410F510FDC542BB686A1A4D601DD411A506504
...

So the problem is that only the first 4bytes) are transferred, the rest are trailing zero's.

Is this related to the fact that I'm doing something wrong, or isn't it possible to cut the binary files properly into chuncks of 1024 and transfer them into a table towards SAP.

Many thanks for your suggestions/support.

Date and Time fields not converted to python objects after last change

After commit 452d36 on Python 2.7 build, abap fields of type T and D are returned as strings and not date and time Python types:

Test:

from pyrfc import Connection
import datetime

USER = 'an_user'
con = Connection(user=USER, passwd='a_password', 
                 ashost='10.0.0.1', sysnr='00', client='000')
response = con.call('BAPI_USER_GET_DETAIL', USERNAME=USER)

assert isinstance(response['LASTMODIFIED']['MODDATE'], datetime.date)
assert isinstance(response['LASTMODIFIED']['MODTIME'], datetime.time)

Please, on the future, change version numbers of builds when doing a fix or change like this.

S4 RFC Connectivity

I'm receiving and error when attempting to connect to an S4 instance over RFC -- has anyone been successful in using this module to connect to S4? Or conversely is there another way to connect with python to S4?

Setting TRACE / RFC_TRACE=3 in destination section of sapnwrfc.ini has no effect

I defined a destination in sapnwrfc.ini (which I copied from demo folder of NWRFC_40-20004568.SAR as followsJ):

DEST=ABC123
ASHOST=ABC123HOSTNAME
SYSNR=123
CLIENT=333
USER=USERNAME
PASSWD=PASSWORD
LANG=DE
RFC_TRACE=3

When I run my script no trace file (.trc) is created in current dir.

But when I uncommet line 30 of sapnwrfc.ini so that I have

DEFAULT
# Trace all connections/destinations, which do not explicitly define
# their own trace level, with level 1. If this value is not set, the
# default is 0. Possible values are 0(off), 1(brief), 2(verbose), 3(full)
RFC_TRACE=3

and then run my script a trace file is created in current dir.

Could not convert from 8400 codepage to 4103 codepage

test:

rel = conn.call('ZRFC_SD_903', OPTION='A')

Traceback (most recent call last):
File "<pyshell#17>", line 1, in
rel = conn.call('ZRFC_SD_903', OPTION='A')
File "pyrfc_pyrfc.pyx", line 363, in pyrfc._pyrfc.Connection.call (pyrfc_pyrfc.c:3955)
File "pyrfc_pyrfc.pyx", line 218, in pyrfc._pyrfc.Connection._error (pyrfc_pyrfc.c:3044)
ExternalRuntimeError: RFC_CONVERSION_FAILURE (rc=22): key=RFC_CONVERSION_FAILURE, message=Could not convert from 8400 codepage to 4103 codepage, rc = 512 [MSG: class=, type=, number=, v1-4:=;;;]

No module named _pyrfc

D:\sap\PyRFC-master>python
Python 2.7.4 (default, Apr 6 2013, 19:55:15) [MSC v.1500 64 bit (AMD64)] on win
32
Type "help", "copyright", "credits" or "license" for more information.

from pyrfc import Connection
Traceback (most recent call last):
File "", line 1, in
File "pyrfc__init__.py", line 22, in
from pyrfc.pyrfc import get_nwrfclib_version, Connection, TypeDescription,
FunctionDescription, Server
ImportError: No module named pyrfc
from pyrfc import Connection
Traceback (most recent call last):
File "", line 1, in
File "pyrfc__init
.py", line 22, in
from pyrfc._pyrfc import get_nwrfclib_version, Connection, TypeDescription,
FunctionDescription, Server
ImportError: No module named _pyrfc

maybe some error in source ,please help me solve this issue,
THanks

Connection.call() not extracting full record (#### symbols in BKTXT)

Hello,

We are experiencing an issue when using Connection.call(). Specifically, certain records appeared to be blank after the first three fields. After doing some digging, we were able to identify the a common theme for records that were being experiencing this problem:

The data BKTXT field in BKPF contained 1-many "odd" characters that were represented in the GUI by the pound/hash sign. It appears that pyRFC can't handle them.

Here is the BKTXT field per the SAP GUI:

bkpf_in_sap

And here is the data exactly how it is returned in the pyrfc.Connection.call(). Note, the data for the record completely cuts off after the BKTXT field. The adjacent records are normal.

bkpf_data

The record is cutting off immediately following BKTXT.

Note we are calling the function module "/BODS/RFC_READ_TABLE2" and we are not using a delimiter. We are using the RECOFFSET.

error in the installation guide

Hi, thanks for your job. I don't know if it's a problem but i was following the instructions to install pyrfc but seems like the egg files are not available in the packages directory. I was looking for in https://pypi.python.org/pypi but there is no package. It's build with sources the only way available to install pyrfc?
Thanks and kind regards
Francisco Pavon

Parallel requests fail

When I try to send multiple RFCs in parallel with the same connection the application crashes - in such a way that I can not even handle it with try ... except.

How to reproduce it:

import pyrfc
def test_parallel():
    from threading import Thread

    conn = pyrfc.Connection( ... )

    print("test_parallel ... start")

    def do_call(iteration):
        print("do_call {}", iteration)
        try:
            print( conn.call('STFC_CONNECTION', REQUTEXT="Hello World! Iteration: {}".format(iteration)) )
        except Exception as e:
            print("Exception in iteration {}: {}".format(iteration, e))

    # just to make sure it's working at least once
    do_call(0)

    t_list = []
    for i in range(1, 10):
        t = Thread(target=do_call, args=(i,))
        t.start()
        t_list.append(t)
    for t in t_list:
        t.join()

    conn.close()

    print("test_parallel ... done")

test_parallel()

Output:

test_parallel ... start

do_call {} 0
{'ECHOTEXT': 'Hello World! Iteration: 0', 'RESPTEXT': 'SAP R/3 Rel. 740 Sysid: BLD Date: 20170623 Time: 090216 Logon_Data: 123/xxx/D'}
do_call {} 1
do_call {} 2
do_call {} 3
do_call {} 4
do_call {} 5
do_call {} 6
do_call {} 7
do_call {} 8
do_call {} 9
Exception in iteration 3: RFC_INVALID_HANDLE (rc=13): key=RFC_INVALID_HANDLE, message=Invalid RFC connection handle: 58766656 [MSG: class=, type=, number=, v1-4:=;;;]
Exception in iteration 6: RFC_INVALID_HANDLE (rc=13): key=RFC_INVALID_HANDLE, message=Invalid RFC connection handle: 58766656 [MSG: class=, type=, number=, v1-4:=;;;]
Exception in iteration 7: RFC_INVALID_HANDLE (rc=13): key=RFC_INVALID_HANDLE, message=Invalid RFC connection handle: 58766656 [MSG: class=, type=, number=, v1-4:=;;;]
Exception in iteration 8: RFC_INVALID_HANDLE (rc=13): key=RFC_INVALID_HANDLE, message=Invalid RFC connection handle: 58766656 [MSG: class=, type=, number=, v1-4:=;;;]
Exception in iteration 5: RFC_INVALID_HANDLE (rc=13): key=RFC_INVALID_HANDLE, message=Invalid RFC connection handle: 58766656 [MSG: class=, type=, number=, v1-4:=;;;]
Exception in iteration 4: RFC_INVALID_HANDLE (rc=13): key=RFC_INVALID_HANDLE, message=Invalid RFC connection handle: 58766656 [MSG: class=, type=, number=, v1-4:=;;;]
Exception in iteration 9: RFC_INVALID_HANDLE (rc=13): key=RFC_INVALID_HANDLE, message=Invalid RFC connection handle: 58766656 [MSG: class=, type=, number=, v1-4:=;;;]
Exception in iteration 2: RFC_COMMUNICATION_FAILURE (rc=1): key=RFC_COMMUNICATION_FAILURE, message=
ERROR program state check for conversation 12958055
TIME Fri Jun 23 09:02:14 2017
RELEASE 721
COMPONENT CPIC (TCP/IP) with Unicode
VERSION 3
RC 471
MODULE r3cpic.c
LINE 6078
DETAIL called function STSEND in state state=BUFFER_DATA2
COUNTER 1
[MSG: class=, type=, number=, v1-4:=;;;]

After the last output, I get a ‘python.exe has stopped working’.

Traceback of the communication failure:

Exception in thread Thread-2:
Traceback (most recent call last):
  File "c:\Python34_64\lib\threading.py", line 920, in _bootstrap_inner
    self.run()
  File "c:\Python34_64\lib\threading.py", line 868, in run
    self._target(*self._args, **self._kwargs)
  File "D:\SAP_RFC_TEST.py", line 51, in do_call
    print( conn.call('STFC_CONNECTION', REQUTEXT="Hello World! Iteration: {}".format(iteration)) )
  File "pyrfc\_pyrfc.pyx", line 363, in pyrfc._pyrfc.Connection.call (pyrfc\_pyrfc.c:4130)
  File "pyrfc\_pyrfc.pyx", line 218, in pyrfc._pyrfc.Connection._error (pyrfc\_pyrfc.c:3153)
pyrfc._exception.CommunicationError: RFC_COMMUNICATION_FAILURE (rc=1): key=RFC_COMMUNICATION_FAILURE, message=
ERROR       program state check for conversation 13613935
TIME        Fri Jun 23 09:12:27 2017
RELEASE     721
COMPONENT   CPIC (TCP/IP) with Unicode
VERSION     3
RC          471
MODULE      r3cpic.c
LINE        6078
DETAIL      called function STSEND in state state=BUFFER_DATA2
COUNTER     1
 [MSG: class=, type=, number=, v1-4:=;;;]

These node-rfc issues might be related:

My system:

  • pyrfc: pyrfc-1.9.4-py3.4-win-amd64
  • OS: Windows 7 64 bit
  • Python: 3.4.3 64 bit

SNC with X509

I am getting the below error when trying to use a cert based authentication. The connection works fine with basic auth.

/XXXX/XXX-engine-cert.pem',snc_lib='XXXXX/libsapcrypto.so',ashost='XXXXXX', sysnr='00', client='001', )
[Thr 140640983607040] Wed Oct 11 15:16:43 2017
[Thr 140640983607040] *** ERROR => SncPEstablishContext() failed for target='p:CN=A4H, OU=SAP-AG, C=DE' [sncxxall_m 3638]
Traceback (most recent call last):
File "", line 1, in
File "src/pyrfc/_pyrfc.pyx", line 164, in pyrfc._pyrfc.Connection.init
File "src/pyrfc/_pyrfc.pyx", line 208, in pyrfc._pyrfc.Connection._open
File "src/pyrfc/_pyrfc.pyx", line 238, in pyrfc._pyrfc.Connection._error
pyrfc._exception.CommunicationError: RFC_COMMUNICATION_FAILURE (rc=1): key=RFC_COMMUNICATION_FAILURE, message=
LOCATION CPIC (TCP/IP) with Unicode
ERROR GSS-API(maj): No credentials were supplied
Unable to establish the security context
target="p:CN=A4H, OU=SAP-AG, C=DE"
TIME Wed Oct 11 15:16:43 2017
RELEASE 721
COMPONENT SNC (Secure Network Communication)
VERSION 6
RC -4
MODULE sncxxall_mt.c
LINE 3604
DETAIL SncPEstablishContext
SYSTEM CALL gss_init_sec_context
COUNTER 7
[MSG: class=, type=, number=, v1-4:=;;;]

What should be passed in parameter x509cert=.......?

load _pyrfc.pyd in Windows also need Microsoft vs runtime

I met a problem during importing pyrfc although I have installed SAPNWRFC before,

import pyrfc
Traceback (most recent call last):
File "", line 1, in
File "C:\Python27\lib\site-packages\pyrfc-1.9.4-py2.7-win-amd64.egg\pyrfc__in
it__.py", line 22, in
from pyrfc._pyrfc import get_nwrfclib_version, Connection, TypeDescription,
FunctionDescription, Server
ImportError: DLL load failed: The specified module could not be found.

I spent a lot of time to investigate the root cause of this. Finally, I found the _pyrfc.pyd may be compiled with MSVS, in my case, MSVS 2015. I downloaded and installed Visual C++ Redistributable for Visual Studio 2015 to resolve this problem.
https://www.microsoft.com/en-us/download/details.aspx?id=48145

I suggest to note the version of Visual Studio to installation manual to avoid similar problem. Thanks.

Python 3.6 wheel

No wheels for python 3.6 exist. Can these be built and released? Thanks!

LogonError since SAP system update to EHP8

Since an recent update of our SAP system to EHP8 I am getting the following error:

LogonError: <Unrepresentable object LogonError. Error:
 UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 45
: ordinal not in range(128)>

Actually I do not use any special characters in logon information. Thus no idea where to look and how to solve that.
Some hints?

My setup:
Python 2.7.10
PyRFC 1.9.3
Windows 7 64bit

Pip support

Wonder why PyRFC is packaged as .egg. Why not use .whl so that one can use pip for installation?

SAP NW RFC Library (libsapnwrfc) Copyrights / Distribution in open source project

I would like to distribute a little library on PyPI which uses PyRFC and thus depends on SAP NW RFC Library.

To make intallation process of my library as easy as possible I would like to include SAP NW RFC files in my package so that users of the library don't need to have a logon on SAP Market Place which may be too big hurdle for some users.

I gues there is no such issue with PyRFC as it is obviously open source but whom can I asked about permission for SAP NW RFC Lib files?

PyRFC & SAP S/4HANA

It seems that SAP HANA is becoming more and more important and SAP S/4HANA and the HANA Cloud Plattform (HCP) will replace SAP ERP in coming years. In that context will PyRFC still be relevant or will there be no use case for it any more?

I am just asking cause I don't understand what role SAP Netweaver will have in context of S/4HANA.

Cheers
Tset

RFC_ABAP_EXCEPTION (rc=5): key=DATA_BUFFER_EXCEEDED

results = conn.call('RFC_READ_TABLE', QUERY_TABLE = '/BIC/OHZOH_PSC05', OPTIONS = options, DELIMITER='|', FIELDS = fields, ROWSKIPS = rowskips, ROWCOUNT = ROWS_AT_A_TIME)
File "src/pyrfc/_pyrfc.pyx", line 377, in pyrfc._pyrfc.Connection.call (src/pyrfc/_pyrfc.c:4507)
File "src/pyrfc/_pyrfc.pyx", line 232, in pyrfc._pyrfc.Connection._error (src/pyrfc/_pyrfc.c:3532)
pyrfc._exception.ABAPApplicationError: RFC_ABAP_EXCEPTION (rc=5): key=DATA_BUFFER_EXCEEDED, message= Number:000 [MSG: class=, type=, number=000, v1-4:=;;;]

I try similar issues like #7 and #38, but I get the same error.

[Python3.5] iteritems() --> items()

I have this code:

def call_bapi(self, bapi, **kwargs):
        try:
            result = self.sap.call(bapi, **kwargs)
            return result
        except:
            raise

failing with

AttributeError: iteritems	
09:26:49.587	DEBUG	Traceback (most recent call last):
  File "c:\users\ME\envs\rf_3564\lib\site-packages\sap_library-0.0.1-py3.5.egg\SAP\SAP.py", line 77, in call_bapi
    result = self.sap.call(bapi, **kwargs)
  File "src/pyrfc/_pyrfc.pyx", line 373, in pyrfc._pyrfc.Connection.call (src/pyrfc\_pyrfc.c:4442)
  File "src/pyrfc/_pyrfc.pyx", line 1543, in pyrfc._pyrfc.fillFunctionParameter (src/pyrfc\_pyrfc.c:18589)
  File "src/pyrfc/_pyrfc.pyx", line 1579, in pyrfc._pyrfc.fillVariable (src/pyrfc\_pyrfc.c:19043)
  File "c:\users\ME\envs\rf_3564\lib\site-packages\robot\utils\dotdict.py", line 28, in __getattr__
    raise AttributeError(key)

A quick google search brought me here which seems to be a similar case?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.