Python UiPath - 如何将 类 与 UiPath.Python.Activities 一起使用

Python UiPath - How to use Classes with UiPath.Python.Activities

这是一张显示 Python 范围 activity(版本 3.6 和目标 x64)的图像:

Python 范围

主要问题是调用python方法之间的关系,第一个用于启动class对象,第二个用于访问class的方法].这是第一次调用 python 属性的图像:

调用Python初始化方法

并且 getNumberPlusOne activity 调用:

调用Python getNumberPlusOne 方法

正在执行的python代码:

class ExampleClass:
    def __init__(self,t,n):
        self.text = t
        self.number = n

    def getNumberPlusOne(self):
        return (self.number+1)

最后,执行第二个Invoke Python方法时报错:

An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is: System.InvalidOperationException: Error invoking Python method ----> System.Runtime.Serialization.InvalidDataContractException: Type 'UiPath.Python.PythonObject' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for other supported types.

知道错误在哪里以及如何与 init 方法中创建的输出对象交互吗?

我相信这个 activity 是为简单的脚本而设计的,而不是整个 classes。 Here's 他们社区论坛上的一篇文章,其中用户 Sergiu.Wittenberger 介绍了更多详细信息。

让我们从加载 Python 脚本 activity 开始:

在我的例子中,局部变量 "pyScript" 是指向 python 对象的指针,即 ExampleClass.

的实例

现在,有调用 Python 方法 activity - 这个允许我们通过名称调用方法。然而,UiPath 似乎无法访问 class 上的方法——您不能只键入 pyScript.MethodName()

所以我们似乎无法访问 class 方法(请证明我在这里错了!),但有一个解决方法,如 Sergio 所示。在您的情况下,您将在 class 之外添加另一个方法以访问或操作您的对象:

class ExampleClass:
    def __init__(self,t,n):
        self.text = t
        self.number = n

    def getNumberPlusOne(self):
        return (self.number+1)


foo = ExampleClass("bar", 42)

def get_number_plus_one():
    return foo.getNumberPlusOne()

请注意,这也意味着该对象是在同一个文件中实例化的:foo。在这一点上,这似乎是与对象交互的唯一选择——同样,我希望有人能证明我是错的。

为了完整起见,结果如下:

我想补充一下上述用户所说的,您必须确保您使用的导入是在全局 site-packages 中,而不是在 venv 中,因为 Studio 无权访问那。

此外,请始终添加:

import os
import sys

sys.path.append(os.path.dirname(os.path.realpath(__file__)))

到代码的开头。同样,实施的限制。 (此处的文档:https://docs.uipath.com/activities/docs/load-script

我认为这样做你也许可以做更复杂的结构,但我还没有测试过。