-
Notifications
You must be signed in to change notification settings - Fork 10
Functions (Client)
If you want to run the function, and you do not need to control the lifetime of the threads, use BasRemoteClient instance for this. In this case, the client itself creates and terminates BAS threads to perform functions.
The run_function()
method returns an instance of the BasFunction
class.
Using it, you can stop the execution of a running function, get the ID of the thread in which it was run, or get the function result using method call function object with await
keyword.
BasFunction
object is awaitable. If you will use code like await function
it will wait for the function to complete and return its result. If you do this again and the function is already completed, the same result will be returned.
Take a look at the examples:
client = BasRemoteClient(options=Options(script_name='TestRemoteControl'))
await client.start()
# Call one function and get the result.
result = await client.run_function('GoogleSearch', {'Query': 'cats'})
# Output results.
print(result)
await client.close()
# Start functions.
function1 = client.run_function('GoogleSearch', {'Query': 'cats'})
function2 = client.run_function('GoogleSearch', {'Query': 'dogs'})
# Wait for both functions to finish.
result = await asyncio.gather(function1, function2)
# Output results.
print(result)
You can also wrap your function call to try/except block in order to handle possible errors that may be returned byfunction. All function errors contains custom error message returned by your script.
try:
await client.run_function('NotExistingFunction')
except Exception as error:
print(error)
The best way to handle errors would be to specify the BasError
type. All errors associated with the library are inherited from this class. As for functions, exception handling can be done using the FunctionError
type.
By calling the stop()
method of a function, you can immediately stop the execution of the function. It can be useful if you want to add timeouts to call your function or you don't want to wait for it to complete.
In the example below, a function is called that takes a very long time, but we stop it after ten seconds of waiting.
# Run function without await.
function = client.run_function('GoogleSearch', {'Query': 'cats'})
# Sleep for 10 seconds.
await asyncio.sleep(10)
# Stop function execution.
await function.stop()
If you want to wait for the function to complete in this case, it is better to use error handling, since the exception will be thrown when the function is stopped.