{"id":18176591,"url":"https://github.com/arya2004/python-executor-library","last_synced_at":"2025-04-09T21:51:49.444Z","repository":{"id":245816541,"uuid":"814063523","full_name":"arya2004/python-executor-library","owner":"arya2004","description":"Local Python Code Execution Abstraction ","archived":false,"fork":false,"pushed_at":"2024-06-25T07:16:46.000Z","size":49,"stargazers_count":3,"open_issues_count":2,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-09T21:51:44.900Z","etag":null,"topics":["c","csharp","hacktoberfest","hacktoberfest-accepted","hacktoberfest2024","nuget"],"latest_commit_sha":null,"homepage":"https://www.nuget.org/packages/PythonExecutorLibrary/","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"cc0-1.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/arya2004.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.txt","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-06-12T09:15:56.000Z","updated_at":"2025-01-04T02:34:28.000Z","dependencies_parsed_at":"2024-06-24T10:35:28.996Z","dependency_job_id":"d44b15b0-033a-412b-89cf-3692e10e5028","html_url":"https://github.com/arya2004/python-executor-library","commit_stats":null,"previous_names":["arya2004/python-executor-library"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arya2004%2Fpython-executor-library","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arya2004%2Fpython-executor-library/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arya2004%2Fpython-executor-library/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arya2004%2Fpython-executor-library/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/arya2004","download_url":"https://codeload.github.com/arya2004/python-executor-library/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248119402,"owners_count":21050754,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["c","csharp","hacktoberfest","hacktoberfest-accepted","hacktoberfest2024","nuget"],"created_at":"2024-11-02T17:09:43.530Z","updated_at":"2025-04-09T21:51:49.414Z","avatar_url":"https://github.com/arya2004.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Python Executor Library\n\n## Overview\n\nThe `PythonExecutorLibrary` is a .NET library that provides functionalities to execute Python scripts, manage Python virtual environments, handle processes, and manage Python packages. This document provides definitions and usage examples for the classes and methods in the library.\n\n___\n\n\n## Classes and Methods\n\n### PythonExecutor\n\n#### `RunPythonScript`\n\n```csharp\npublic static string RunPythonScript(string pythonExecutablePath, string scriptPath, string arguments)\n```\n\nExecutes a Python script with the specified arguments.\n\n- **Parameters**:\n  - `pythonExecutablePath` (string): The path to the Python executable.\n  - `scriptPath` (string): The path to the Python script.\n  - `arguments` (string): The arguments to pass to the script.\n\n- **Returns**: The output from the script execution.\n\n___\n\n### PythonPackageManager\n\n#### `InstallPackageAsync`\n\n```csharp\npublic static async Task\u003cbool\u003e InstallPackageAsync(string fullPythonPath, string packageName, string args = \"\")\n```\n\nInstalls a Python package asynchronously.\n\n- **Parameters**:\n  - `fullPythonPath` (string): The full path to the Python executable.\n  - `packageName` (string): The name of the package to install.\n  - `args` (string): Additional arguments for the pip install command.\n\n- **Returns**: A task that represents the asynchronous operation. The task result contains a boolean indicating whether the installation was successful.\n\n#### `PackageExistsAsync`\n\n```csharp\npublic static async Task\u003cbool\u003e PackageExistsAsync(string fullPythonPath, string packageName)\n```\n\nChecks if a Python package is installed asynchronously.\n\n- **Parameters**:\n  - `fullPythonPath` (string): The full path to the Python executable.\n  - `packageName` (string): The name of the package to check.\n\n- **Returns**: A task that represents the asynchronous operation. The task result contains a boolean indicating whether the package is installed.\n\n#### `IsPackageHealthyAsync`\n\n```csharp\npublic static async Task\u003cbool\u003e IsPackageHealthyAsync(string fullPythonPath, string packageName)\n```\n\nChecks if a Python package is healthy (i.e., can be imported without error) asynchronously.\n\n- **Parameters**:\n  - `fullPythonPath` (string): The full path to the Python executable.\n  - `packageName` (string): The name of the package to check.\n\n- **Returns**: A task that represents the asynchronous operation. The task result contains a boolean indicating whether the package is healthy.\n\n#### `GetPackageLocationAsync`\n\n```csharp\npublic static async Task\u003cstring\u003e GetPackageLocationAsync(string fullPythonPath, string packageName)\n```\n\nGets the location of a Python package asynchronously.\n\n- **Parameters**:\n  - `fullPythonPath` (string): The full path to the Python executable.\n  - `packageName` (string): The name of the package to locate.\n\n- **Returns**: A task that represents the asynchronous operation. The task result contains the location of the package if found, otherwise null.\n\n#### `InstallPipAsync`\n\n```csharp\npublic static async Task\u003cbool\u003e InstallPipAsync(string fullPythonPath)\n```\n\nInstalls pip asynchronously.\n\n- **Parameters**:\n  - `fullPythonPath` (string): The full path to the Python executable.\n\n- **Returns**: A task that represents the asynchronous operation. The task result contains a boolean indicating whether the installation was successful.\n\n#### `InstallPackage`\n\n```csharp\npublic static bool InstallPackage(string fullPythonPath, string packageName, string args = \"\")\n```\n\nInstalls a Python package synchronously.\n\n- **Parameters**:\n  - `fullPythonPath` (string): The full path to the Python executable.\n  - `packageName` (string): The name of the package to install.\n  - `args` (string): Additional arguments for the pip install command.\n\n- **Returns**: A boolean indicating whether the installation was successful.\n\n#### `PackageExists`\n\n```csharp\npublic static bool PackageExists(string fullPythonPath, string packageName)\n```\n\nChecks if a Python package is installed synchronously.\n\n- **Parameters**:\n  - `fullPythonPath` (string): The full path to the Python executable.\n  - `packageName` (string): The name of the package to check.\n\n- **Returns**: A boolean indicating whether the package is installed.\n\n#### `IsPackageHealthy`\n\n```csharp\npublic static bool IsPackageHealthy(string fullPythonPath, string packageName)\n```\n\nChecks if a Python package is healthy (i.e., can be imported without error) synchronously.\n\n- **Parameters**:\n  - `fullPythonPath` (string): The full path to the Python executable.\n  - `packageName` (string): The name of the package to check.\n\n- **Returns**: A boolean indicating whether the package is healthy.\n\n#### `GetPackageLocation`\n\n```csharp\npublic static string GetPackageLocation(string fullPythonPath, string packageName)\n```\n\nGets the location of a Python package synchronously.\n\n- **Parameters**:\n  - `fullPythonPath` (string): The full path to the Python executable.\n  - `packageName` (string): The name of the package to locate.\n\n- **Returns**: The location of the package if found, otherwise null.\n\n#### `InstallPip`\n\n```csharp\npublic static bool InstallPip(string fullPythonPath)\n```\n\nInstalls pip synchronously.\n\n- **Parameters**:\n  - `fullPythonPath` (string): The full path to the Python executable.\n\n- **Returns**: A boolean indicating whether the installation was successful.\n\n### Usage Examples\n\n#### Running a Python Script\n\n```csharp\nstring pythonPath = @\"C:\\Python39\\python.exe\";\nstring scriptPath = @\"C:\\Scripts\\my_script.py\";\nstring arguments = \"arg1 arg2\";\n\nstring output = PythonExecutor.RunPythonScript(pythonPath, scriptPath, arguments);\nConsole.WriteLine(output);\n```\n\n\n\n#### Installing a Python Package Asynchronously\n\n```csharp\nstring pythonPath = @\"C:\\Python39\\python.exe\";\nstring packageName = \"requests\";\n\nbool isInstalled = await PythonPackageManager.InstallPackageAsync(pythonPath, packageName);\nConsole.WriteLine(\"Package Installed: \" + isInstalled);\n```\n\n#### Checking if a Package is Installed\n\n```csharp\nstring pythonPath = @\"C:\\Python39\\python.exe\";\nstring packageName = \"requests\";\n\nbool exists = PythonPackageManager.PackageExists(pythonPath, packageName);\nConsole.WriteLine(\"Package Exists: \" + exists);\n```\n\n#### Checking Package Health\n\n```csharp\nstring pythonPath = @\"C:\\Python39\\python.exe\";\nstring packageName = \"requests\";\n\nbool isHealthy = PythonPackageManager.IsPackageHealthy(pythonPath, packageName);\nConsole.WriteLine(\"Package Healthy: \" + isHealthy);\n```\n\n#### Installing pip Asynchronously\n\n```csharp\nstring pythonPath = @\"C:\\Python39\\python.exe\";\n\nbool isPipInstalled\n\n = await PythonPackageManager.InstallPipAsync(pythonPath);\nConsole.WriteLine(\"pip Installed: \" + isPipInstalled);\n```\n\n\n___\n\n### PythonCodeValidator\n\nThe `PythonCodeValidator` class contains methods to validate Python code. This class is static and does not require instantiation.\n\n#### Methods\n\n##### ContainsImportOrPrint\n\n```csharp\npublic static bool ContainsImportOrPrint(string pythonCode)\n```\n\n**Description:**\n\nThe `ContainsImportOrPrint` method checks if the given Python code contains 'import' or 'print' statements. It uses regular expressions to search for these keywords in a case-insensitive manner.\n\n**Parameters:**\n\n- `pythonCode` (`string`): The Python code to validate. It can be a single line or multiple lines of code.\n\n**Returns:**\n\n- `bool`: Returns `true` if the code contains 'import' or 'print' statements; otherwise, returns `false`.\n\n**Usage:**\n\n```csharp\nusing System;\nusing PythonExecutorLibrary;\n\nclass Program\n{\n    static void Main()\n    {\n        string code1 = \"import os\\nprint('Hello, world!')\";\n        string code2 = \"def add(a, b):\\n    return a + b\";\n\n        bool result1 = PythonCodeValidator.ContainsImportOrPrint(code1); // Returns true\n        bool result2 = PythonCodeValidator.ContainsImportOrPrint(code2); // Returns false\n\n        Console.WriteLine($\"Code 1 contains 'import' or 'print': {result1}\");\n        Console.WriteLine($\"Code 2 contains 'import' or 'print': {result2}\");\n    }\n}\n```\n\n___\n\n### PythonExecutor\n\nThe `PythonExecutor` class provides methods to execute Python code. This class supports both synchronous and asynchronous execution.\n\n#### Properties\n\n##### Interval\n\n```csharp\npublic TimeSpan Interval { get; set; }\n```\n\n**Description:**\n\nGets or sets the interval between executions.\n\n##### LastExecutionTime\n\n```csharp\npublic DateTime LastExecutionTime { get; set; }\n```\n\n**Description:**\n\nGets or sets the last execution time.\n\n##### TimeLimitInSeconds\n\n```csharp\npublic int TimeLimitInSeconds { get; set; }\n```\n\n**Description:**\n\nGets or sets the time limit for executing Python code in seconds.\n\n#### Constructors\n\n##### PythonExecutor(TimeSpan _dateTimeOffset, int processTimeLimitInSeconds)\n\n```csharp\npublic PythonExecutor(TimeSpan _dateTimeOffset, int processTimeLimitInSeconds)\n```\n\n**Description:**\n\nInitializes a new instance of the `PythonExecutor` class with a specified interval and time limit.\n\n**Parameters:**\n\n- `_dateTimeOffset` (`TimeSpan`): The interval between executions.\n- `processTimeLimitInSeconds` (`int`): The time limit for executing Python code in seconds.\n\n##### PythonExecutor(int processTimeLimitInSeconds)\n\n```csharp\npublic PythonExecutor(int processTimeLimitInSeconds)\n```\n\n**Description:**\n\nInitializes a new instance of the `PythonExecutor` class with a specified time limit.\n\n**Parameters:**\n\n- `processTimeLimitInSeconds` (`int`): The time limit for executing Python code in seconds.\n\n#### Methods\n\n##### ExecutePythonCodeAsync\n\n```csharp\npublic async Task\u003c(string output, string error)\u003e ExecutePythonCodeAsync(string fullPythonPath, string code)\n```\n\n**Description:**\n\nExecutes Python code asynchronously.\n\n**Parameters:**\n\n- `fullPythonPath` (`string`): The full path to the Python executable.\n- `code` (`string`): The Python code to execute.\n\n**Returns:**\n\n- `Task\u003c(string output, string error)\u003e`: A tuple containing the standard output and standard error from the Python process.\n\n**Usage:**\n\n```csharp\nusing System;\nusing System.Threading.Tasks;\nusing PythonExecutorLibrary;\n\nclass Program\n{\n    static async Task Main()\n    {\n        var executor = new PythonExecutor(5);\n        var result = await executor.ExecutePythonCodeAsync(\"/usr/bin/python3\", \"print('Hello, world!')\");\n        Console.WriteLine($\"Output: {result.output}\");\n        Console.WriteLine($\"Error: {result.error}\");\n    }\n}\n```\n\n##### ExecuteMultiplePythonCodeAsync\n\n```csharp\npublic async Task\u003c(string[] output, string error)\u003e ExecuteMultiplePythonCodeAsync(string fullPythonPath, string[] args)\n```\n\n**Description:**\n\nExecutes multiple Python code snippets asynchronously.\n\n**Parameters:**\n\n- `fullPythonPath` (`string`): The full path to the Python executable.\n- `args` (`string[]`): An array of Python code snippets to execute.\n\n**Returns:**\n\n- `Task\u003c(string[] output, string error)\u003e`: A tuple containing an array of standard outputs and the standard error from the Python process.\n\n**Usage:**\n\n```csharp\nusing System;\nusing System.Threading.Tasks;\nusing PythonExecutorLibrary;\n\nclass Program\n{\n    static async Task Main()\n    {\n        var executor = new PythonExecutor(5);\n        string[] scripts = { \"print('Script 1')\", \"print('Script 2')\" };\n        var result = await executor.ExecuteMultiplePythonCodeAsync(\"/usr/bin/python3\", scripts);\n        foreach (var output in result.output)\n        {\n            Console.WriteLine($\"Output: {output}\");\n        }\n        Console.WriteLine($\"Error: {result.error}\");\n    }\n}\n```\n\n##### ExecutePythonCode\n\n```csharp\npublic (string output, string error) ExecutePythonCode(string fullPythonPath, string code)\n```\n\n**Description:**\n\nExecutes Python code synchronously.\n\n**Parameters:**\n\n- `fullPythonPath` (`string`): The full path to the Python executable.\n- `code` (`string`): The Python code to execute.\n\n**Returns:**\n\n- `(string output, string error)`: A tuple containing the standard output and standard error from the Python process.\n\n**Usage:**\n\n```csharp\nusing System;\nusing PythonExecutorLibrary;\n\nclass Program\n{\n    static void Main()\n    {\n        var executor = new PythonExecutor(5);\n        var result = executor.ExecutePythonCode(\"/usr/bin/python3\", \"print('Hello, world!')\");\n        Console.WriteLine($\"Output: {result.output}\");\n        Console.WriteLine($\"Error: {result.error}\");\n    }\n}\n```\n\n## Example\n\nHere is a complete example demonstrating how to use both the `PythonCodeValidator` and `PythonExecutor` classes:\n\n```csharp\nusing System;\nusing System.Threading.Tasks;\nusing PythonExecutorLibrary;\n\nclass Program\n{\n    static async Task Main()\n    {\n        // Validate Python code\n        string code1 = \"import os\\nprint('Hello, world!')\";\n        string code2 = \"def add(a, b):\\n    return a + b\";\n\n        bool result1 = PythonCodeValidator.ContainsImportOrPrint(code1); // Returns true\n        bool result2 = PythonCodeValidator.ContainsImportOrPrint(code2); // Returns false\n\n        Console.WriteLine($\"Code 1 contains 'import' or 'print': {result1}\");\n        Console.WriteLine($\"Code 2 contains 'import' or 'print': {result2}\");\n\n        // Execute Python code asynchronously\n        var executor = new PythonExecutor(5);\n        var asyncResult = await executor.ExecutePythonCodeAsync(\"/usr/bin/python3\", \"print('Hello, async world!')\");\n        Console.WriteLine($\"Async Output: {asyncResult.output}\");\n        Console.WriteLine($\"Async Error: {asyncResult.error}\");\n\n        // Execute multiple Python code snippets asynchronously\n        string[] scripts = { \"print('Script 1')\", \"print('Script 2')\" };\n        var multiResult = await executor.ExecuteMultiplePythonCodeAsync(\"/usr/bin/python3\", scripts);\n        foreach (var output in multiResult.output)\n        {\n            Console.WriteLine($\"Multi Output: {output}\");\n        }\n        Console.WriteLine($\"Multi Error: {multiResult.error}\");\n\n        // Execute Python code synchronously\n        var syncResult = executor.ExecutePythonCode(\"/usr/bin/python3\", \"print('Hello, sync world!')\");\n        Console.WriteLine($\"Sync Output: {syncResult.output}\");\n        Console.WriteLine($\"Sync Error: {syncResult.error}\");\n    }\n}\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Farya2004%2Fpython-executor-library","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Farya2004%2Fpython-executor-library","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Farya2004%2Fpython-executor-library/lists"}