예제 #1
0
        public void Execute(string code)
        {
            using (var cts = new CancellationTokenSource((int)Timeout * 1000))
            {
                try
                {
                    var request = new PythonRequest()
                    {
                        RequestType = RequestType.Execute,
                        Code        = code
                    };

                    PythonResponse response = RequestAsync(request, cts.Token);
                    cts.Token.ThrowIfCancellationRequested();
                    response.ThrowExceptionIfNeeded();
                }
                catch (Exception e)
                {
                    if (cts.IsCancellationRequested)
                    {
                        throw new TimeoutException(UiPath_Python.TimeoutException);
                    }
                    Trace.TraceError($"Python exception: {e}");
                    throw;
                }
            }
        }
예제 #2
0
        internal void Start()
        {
            //string serviceAddress = Config.MakeServiceAddress(typeof(T), Process.GetCurrentProcess().Id);
            string serviceAddress = string.Empty;

            Trace.TraceInformation($"Trying to start PyService service.");
            try
            {
                pipeServer =
                    new NamedPipeServerStream(Process.GetCurrentProcess().Id.ToString(),
                                              PipeDirection.InOut, 1);

                // Wait for a client to connect
                pipeServer.WaitForConnection();

                using (var streamReader = new StreamReader(pipeServer, _utf8Encoding, false, _defaultBufferSize,
                                                           leaveOpen: true))
                {
                    var request = PythonRequest.Deserialize(streamReader.ReadLine());
                    Console.WriteLine(request.RequestType.ToString());
                }

                Trace.TraceInformation($"PyService service {serviceAddress} started successfully");
            }
            catch (Exception e)
            {
                Trace.TraceError($"Error starting PyService service: {e}");
                throw;
            }
        }
예제 #3
0
        /// <summary>
        /// Writes the serialized Python request to the named pipe. Waits from the request to be read on Python side.
        /// Then reads the response from python(json) an deserializes it to PythonRespnse
        /// </summary>
        /// <param name="request"></param>
        /// <param name="ct"></param>
        /// <returns></returns>
        public PythonResponse RequestAsync(PythonRequest request, CancellationToken ct)
        {
            using (CancellationTokenRegistration ctr = ct.Register(() => OnCancellationRequested()))
            {
                using (var streamWriter = new StreamWriter(ClientStream, _utf8Encoding, _defaultBufferSize,
                                                           leaveOpen: true)
                {
                    AutoFlush = true
                })
                {
                    Trace.TraceInformation("Sending information to Python.");
                    streamWriter.WriteLine(request.Serialize());
                }

                ct.ThrowIfCancellationRequested();
                bool isWindows = true;
#if NETCOREAPP
                if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    isWindows = false;
                }
#endif
                if (isWindows)
                {
                    ClientStream.WaitForPipeDrain();
                }

                using (var streamReader = new StreamReader(ClientStream, _utf8Encoding, false, _defaultBufferSize,
                                                           leaveOpen: true))
                {
                    return(PythonResponse.Deserialize(streamReader.ReadLine()));
                }
            }
        }
예제 #4
0
        public Argument Convert(Guid obj, string t)
        {
            using (var cts = new CancellationTokenSource((int)Timeout * 1000))
            {
                try
                {
                    var request = new PythonRequest()
                    {
                        RequestType = RequestType.Convert,
                        Instance    = obj,
                        Type        = t
                    };

                    PythonResponse response = RequestAsync(request, cts.Token);
                    cts.Token.ThrowIfCancellationRequested();
                    response.ThrowExceptionIfNeeded();
                    return(response.Argument);
                }
                catch (Exception e)
                {
                    if (cts.IsCancellationRequested)
                    {
                        throw new TimeoutException(UiPath_Python.TimeoutException);
                    }
                    Trace.TraceError($"Python exception: {e}");
                    throw;
                }
            }
        }
예제 #5
0
        public Guid LoadScript(string code)
        {
            using (var cts = new CancellationTokenSource((int)Timeout * 1000))
            {
                try
                {
                    var request = new PythonRequest()
                    {
                        RequestType = RequestType.LoadScript,
                        Code        = code
                    };

                    PythonResponse response = RequestAsync(request, cts.Token);

                    cts.Token.ThrowIfCancellationRequested();

                    Trace.TraceInformation("LoadScript Guid:: " + response.Guid);

                    return(response.Guid);
                }
                catch (Exception e)
                {
                    if (cts.IsCancellationRequested)
                    {
                        throw new TimeoutException(UiPath_Python.TimeoutException);
                    }
                    Trace.TraceError($"Python exception: {e}");
                    throw;
                }
            }
        }
예제 #6
0
        public Guid InvokeMethod(Guid instance, string method, IEnumerable <Argument> args)
        {
            using (var cts = new CancellationTokenSource((int)Timeout * 1000))
            {
                try
                {
                    var request = new PythonRequest()
                    {
                        RequestType = RequestType.InvokeMethod,
                        Instance    = instance,
                        Method      = method,
                        Arguments   = args
                    };

                    PythonResponse response = RequestAsync(request, cts.Token);
                    cts.Token.ThrowIfCancellationRequested();
                    response.ThrowExceptionIfNeeded();
                    return(response.Guid);
                }
                catch (Exception e)
                {
                    if (cts.IsCancellationRequested)
                    {
                        throw new TimeoutException(UiPath_Python.TimeoutException);
                    }
                    Trace.TraceError($"Python exception: {e}");
                    throw;
                }
            }
        }
예제 #7
0
        public void Initialize(string path, string libraryPath, Version version, string workingFolder)
        {
            using (var cts = new CancellationTokenSource((int)Timeout * 1000))
            {
                try
                {
                    var request = new PythonRequest()
                    {
                        RequestType   = RequestType.Initialize,
                        ScriptPath    = path,
                        LibraryPath   = libraryPath,
                        PythonVersion = version.ToString(),
                        WorkingFolder = workingFolder
                    };

                    PythonResponse response = RequestAsync(request, Token);
                    Token.ThrowIfCancellationRequested();
                    response.ThrowExceptionIfNeeded();
                }
                catch (Exception e)
                {
                    if (cts.IsCancellationRequested)
                    {
                        throw new TimeoutException(UiPath_Python.TimeoutException);
                    }
                    Trace.TraceError($"Python exception: {e}");
                    throw;
                }
            }
        }
예제 #8
0
        public string GetSuggestion()
        {
            PythonRequest pr = new PythonRequest();

            string suggestion = pr.run_cmd();

            return(suggestion);
        }
예제 #9
0
        private void InitScope(ScriptSource script)
        {
            Request = new PythonRequest();

            Scope.SetVariable("request", Request);
            Scope.SetVariable("self", peripheral);
            Scope.SetVariable("size", peripheral.Size);

            source = script;
        }
        private void InitScope(ScriptSource script)
        {
            Request = new PythonRequest();

            Scope.SetVariable("request", Request);
            Scope.SetVariable("self", peripheral);
            Scope.SetVariable("size", peripheral.Size);

            source = script;
        }
 public ProcessStartInfo CreateForExecution(PythonRequest request)
 {
     return(new ProcessStartInfo
     {
         FileName = FindPythonExeFilePath(),
         Arguments = CreateArgumentsString(request),
         UseShellExecute = false,
         RedirectStandardOutput = true,
         RedirectStandardError = true
     });
 }
 public ProcessStartInfo CreateForListening(PythonRequest request)
 {
     return(new ProcessStartInfo
     {
         FileName = FindPythonExeFilePath(),
         Arguments = CreateArgumentsString(request),
         UseShellExecute = false,
         RedirectStandardInput = true,
         RedirectStandardOutput = true,
         RedirectStandardError = true,
         CreateNoWindow = true,
         WindowStyle = ProcessWindowStyle.Hidden
     });
 }
예제 #13
0
        public void Shutdown()
        {
            using (var cts = new CancellationTokenSource((int)Timeout * 1000))
            {
                var request = new PythonRequest()
                {
                    RequestType = RequestType.Shutdown
                };

                PythonResponse response = RequestAsync(request, cts.Token);

                cts.Token.ThrowIfCancellationRequested();
            }
        }
        private static string CreateArgumentsString(PythonRequest request)
        {
            var sb = new StringBuilder();

            sb.Append(request.FilePath);
            sb.Append(" ");

            sb.Append(request.MethodName);
            sb.Append(" ");

            foreach (var arg in request.Arguments)
            {
                sb.Append(arg.AsString());
                sb.Append(" ");
            }

            var result = sb.ToString();

            return(result);
        }
예제 #15
0
        internal async void RunServer()
        {
            PythonResponse response = new PythonResponse
            {
                ResultState = ResultState.Successful
            };

            pipeName   = Process.GetCurrentProcess().Id.ToString();
            pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte,
                                                   PipeOptions.Asynchronous);

            pipeServer.WaitForConnection();

            using (var streamReader = new StreamReader(pipeServer, _utf8Encoding, false, _defaultBufferSize,
                                                       leaveOpen: true))
                using (var streamWriter = new StreamWriter(pipeServer, _utf8Encoding, _defaultBufferSize,
                                                           leaveOpen: true)
                {
                    AutoFlush = true
                })

                    while (true)
                    {
                        try
                        {
                            var request = PythonRequest.Deserialize(await streamReader.ReadLineAsync());

                            switch (request.RequestType)
                            {
                            case RequestType.Initialize:
                                Initialize(request.ScriptPath, request.LibraryPath, (Version)Enum.Parse(typeof(Version), request.PythonVersion), request.WorkingFolder);
                                response.ResultState = ResultState.Successful;
                                streamWriter.WriteLine(response.Serialize());

                                break;

                            case RequestType.Shutdown:
                                response = new PythonResponse
                                {
                                    ResultState = ResultState.Successful
                                };

                                streamWriter.WriteLine(response.Serialize());
                                Shutdown();
                                break;

                            case RequestType.Execute:
                                Execute(request.Code);
                                response = new PythonResponse
                                {
                                    ResultState = ResultState.Successful
                                };
                                streamWriter.WriteLine(response.Serialize());
                                break;

                            case RequestType.LoadScript:
                                var guid = LoadScript(request.Code);
                                response = new PythonResponse
                                {
                                    ResultState = ResultState.Successful,
                                    Guid        = guid
                                };

                                streamWriter.WriteLine(response.Serialize());
                                break;

                            case RequestType.InvokeMethod:
                                var guidI = InvokeMethod(request.Instance, request.Method, request.Arguments);
                                response = new PythonResponse
                                {
                                    ResultState = ResultState.Successful
                                };
                                response.Guid = guidI;
                                streamWriter.WriteLine(response.Serialize());
                                break;

                            case RequestType.Convert:
                                Argument arg = Convert(request.Instance, request.Type);
                                response = new PythonResponse
                                {
                                    Argument    = arg,
                                    ResultState = ResultState.Successful
                                };

                                streamWriter.WriteLine(response.Serialize());
                                break;

                            default:
                                Shutdown();
                                break;
                            }

                            WaitForPipeDrain(pipeServer);
                        }
                        catch (Exception ex)
                        {
                            response = new PythonResponse
                            {
                                ResultState = ResultState.InstantiationException,
                            };
                            response.Errors = new List <string>();
                            response.Errors.Add(ex.Message);

                            streamWriter.WriteLine(response.Serialize());
                            WaitForPipeDrain(pipeServer);
                            throw;
                        }
                    }
        }