PythonExecutorLibrary 1.1.0
dotnet add package PythonExecutorLibrary --version 1.1.0
NuGet\Install-Package PythonExecutorLibrary -Version 1.1.0
<PackageReference Include="PythonExecutorLibrary" Version="1.1.0" />
<PackageVersion Include="PythonExecutorLibrary" Version="1.1.0" />
<PackageReference Include="PythonExecutorLibrary" />
paket add PythonExecutorLibrary --version 1.1.0
#r "nuget: PythonExecutorLibrary, 1.1.0"
#:package PythonExecutorLibrary@1.1.0
#addin nuget:?package=PythonExecutorLibrary&version=1.1.0
#tool nuget:?package=PythonExecutorLibrary&version=1.1.0
Python Executor Library
Overview
The 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.
Classes and Methods
PythonExecutor
RunPythonScript
public static string RunPythonScript(string pythonExecutablePath, string scriptPath, string arguments)
Executes a Python script with the specified arguments.
Parameters:
pythonExecutablePath
(string): The path to the Python executable.scriptPath
(string): The path to the Python script.arguments
(string): The arguments to pass to the script.
Returns: The output from the script execution.
PythonPackageManager
InstallPackageAsync
public static async Task<bool> InstallPackageAsync(string fullPythonPath, string packageName, string args = "")
Installs a Python package asynchronously.
Parameters:
fullPythonPath
(string): The full path to the Python executable.packageName
(string): The name of the package to install.args
(string): Additional arguments for the pip install command.
Returns: A task that represents the asynchronous operation. The task result contains a boolean indicating whether the installation was successful.
PackageExistsAsync
public static async Task<bool> PackageExistsAsync(string fullPythonPath, string packageName)
Checks if a Python package is installed asynchronously.
Parameters:
fullPythonPath
(string): The full path to the Python executable.packageName
(string): The name of the package to check.
Returns: A task that represents the asynchronous operation. The task result contains a boolean indicating whether the package is installed.
IsPackageHealthyAsync
public static async Task<bool> IsPackageHealthyAsync(string fullPythonPath, string packageName)
Checks if a Python package is healthy (i.e., can be imported without error) asynchronously.
Parameters:
fullPythonPath
(string): The full path to the Python executable.packageName
(string): The name of the package to check.
Returns: A task that represents the asynchronous operation. The task result contains a boolean indicating whether the package is healthy.
GetPackageLocationAsync
public static async Task<string> GetPackageLocationAsync(string fullPythonPath, string packageName)
Gets the location of a Python package asynchronously.
Parameters:
fullPythonPath
(string): The full path to the Python executable.packageName
(string): The name of the package to locate.
Returns: A task that represents the asynchronous operation. The task result contains the location of the package if found, otherwise null.
InstallPipAsync
public static async Task<bool> InstallPipAsync(string fullPythonPath)
Installs pip asynchronously.
Parameters:
fullPythonPath
(string): The full path to the Python executable.
Returns: A task that represents the asynchronous operation. The task result contains a boolean indicating whether the installation was successful.
InstallPackage
public static bool InstallPackage(string fullPythonPath, string packageName, string args = "")
Installs a Python package synchronously.
Parameters:
fullPythonPath
(string): The full path to the Python executable.packageName
(string): The name of the package to install.args
(string): Additional arguments for the pip install command.
Returns: A boolean indicating whether the installation was successful.
PackageExists
public static bool PackageExists(string fullPythonPath, string packageName)
Checks if a Python package is installed synchronously.
Parameters:
fullPythonPath
(string): The full path to the Python executable.packageName
(string): The name of the package to check.
Returns: A boolean indicating whether the package is installed.
IsPackageHealthy
public static bool IsPackageHealthy(string fullPythonPath, string packageName)
Checks if a Python package is healthy (i.e., can be imported without error) synchronously.
Parameters:
fullPythonPath
(string): The full path to the Python executable.packageName
(string): The name of the package to check.
Returns: A boolean indicating whether the package is healthy.
GetPackageLocation
public static string GetPackageLocation(string fullPythonPath, string packageName)
Gets the location of a Python package synchronously.
Parameters:
fullPythonPath
(string): The full path to the Python executable.packageName
(string): The name of the package to locate.
Returns: The location of the package if found, otherwise null.
InstallPip
public static bool InstallPip(string fullPythonPath)
Installs pip synchronously.
Parameters:
fullPythonPath
(string): The full path to the Python executable.
Returns: A boolean indicating whether the installation was successful.
Usage Examples
Running a Python Script
string pythonPath = @"C:\Python39\python.exe";
string scriptPath = @"C:\Scripts\my_script.py";
string arguments = "arg1 arg2";
string output = PythonExecutor.RunPythonScript(pythonPath, scriptPath, arguments);
Console.WriteLine(output);
Installing a Python Package Asynchronously
string pythonPath = @"C:\Python39\python.exe";
string packageName = "requests";
bool isInstalled = await PythonPackageManager.InstallPackageAsync(pythonPath, packageName);
Console.WriteLine("Package Installed: " + isInstalled);
Checking if a Package is Installed
string pythonPath = @"C:\Python39\python.exe";
string packageName = "requests";
bool exists = PythonPackageManager.PackageExists(pythonPath, packageName);
Console.WriteLine("Package Exists: " + exists);
Checking Package Health
string pythonPath = @"C:\Python39\python.exe";
string packageName = "requests";
bool isHealthy = PythonPackageManager.IsPackageHealthy(pythonPath, packageName);
Console.WriteLine("Package Healthy: " + isHealthy);
Installing pip Asynchronously
string pythonPath = @"C:\Python39\python.exe";
bool isPipInstalled
= await PythonPackageManager.InstallPipAsync(pythonPath);
Console.WriteLine("pip Installed: " + isPipInstalled);
PythonCodeValidator
The PythonCodeValidator
class contains methods to validate Python code. This class is static and does not require instantiation.
Methods
ContainsImportOrPrint
public static bool ContainsImportOrPrint(string pythonCode)
Description:
The 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.
Parameters:
pythonCode
(string
): The Python code to validate. It can be a single line or multiple lines of code.
Returns:
bool
: Returnstrue
if the code contains 'import' or 'print' statements; otherwise, returnsfalse
.
Usage:
using System;
using PythonExecutorLibrary;
class Program
{
static void Main()
{
string code1 = "import os\nprint('Hello, world!')";
string code2 = "def add(a, b):\n return a + b";
bool result1 = PythonCodeValidator.ContainsImportOrPrint(code1); // Returns true
bool result2 = PythonCodeValidator.ContainsImportOrPrint(code2); // Returns false
Console.WriteLine($"Code 1 contains 'import' or 'print': {result1}");
Console.WriteLine($"Code 2 contains 'import' or 'print': {result2}");
}
}
PythonExecutor
The PythonExecutor
class provides methods to execute Python code. This class supports both synchronous and asynchronous execution.
Properties
Interval
public TimeSpan Interval { get; set; }
Description:
Gets or sets the interval between executions.
LastExecutionTime
public DateTime LastExecutionTime { get; set; }
Description:
Gets or sets the last execution time.
TimeLimitInSeconds
public int TimeLimitInSeconds { get; set; }
Description:
Gets or sets the time limit for executing Python code in seconds.
Constructors
PythonExecutor(TimeSpan _dateTimeOffset, int processTimeLimitInSeconds)
public PythonExecutor(TimeSpan _dateTimeOffset, int processTimeLimitInSeconds)
Description:
Initializes a new instance of the PythonExecutor
class with a specified interval and time limit.
Parameters:
_dateTimeOffset
(TimeSpan
): The interval between executions.processTimeLimitInSeconds
(int
): The time limit for executing Python code in seconds.
PythonExecutor(int processTimeLimitInSeconds)
public PythonExecutor(int processTimeLimitInSeconds)
Description:
Initializes a new instance of the PythonExecutor
class with a specified time limit.
Parameters:
processTimeLimitInSeconds
(int
): The time limit for executing Python code in seconds.
Methods
ExecutePythonCodeAsync
public async Task<(string output, string error)> ExecutePythonCodeAsync(string fullPythonPath, string code)
Description:
Executes Python code asynchronously.
Parameters:
fullPythonPath
(string
): The full path to the Python executable.code
(string
): The Python code to execute.
Returns:
Task<(string output, string error)>
: A tuple containing the standard output and standard error from the Python process.
Usage:
using System;
using System.Threading.Tasks;
using PythonExecutorLibrary;
class Program
{
static async Task Main()
{
var executor = new PythonExecutor(5);
var result = await executor.ExecutePythonCodeAsync("/usr/bin/python3", "print('Hello, world!')");
Console.WriteLine($"Output: {result.output}");
Console.WriteLine($"Error: {result.error}");
}
}
ExecuteMultiplePythonCodeAsync
public async Task<(string[] output, string error)> ExecuteMultiplePythonCodeAsync(string fullPythonPath, string[] args)
Description:
Executes multiple Python code snippets asynchronously.
Parameters:
fullPythonPath
(string
): The full path to the Python executable.args
(string[]
): An array of Python code snippets to execute.
Returns:
Task<(string[] output, string error)>
: A tuple containing an array of standard outputs and the standard error from the Python process.
Usage:
using System;
using System.Threading.Tasks;
using PythonExecutorLibrary;
class Program
{
static async Task Main()
{
var executor = new PythonExecutor(5);
string[] scripts = { "print('Script 1')", "print('Script 2')" };
var result = await executor.ExecuteMultiplePythonCodeAsync("/usr/bin/python3", scripts);
foreach (var output in result.output)
{
Console.WriteLine($"Output: {output}");
}
Console.WriteLine($"Error: {result.error}");
}
}
ExecutePythonCode
public (string output, string error) ExecutePythonCode(string fullPythonPath, string code)
Description:
Executes Python code synchronously.
Parameters:
fullPythonPath
(string
): The full path to the Python executable.code
(string
): The Python code to execute.
Returns:
(string output, string error)
: A tuple containing the standard output and standard error from the Python process.
Usage:
using System;
using PythonExecutorLibrary;
class Program
{
static void Main()
{
var executor = new PythonExecutor(5);
var result = executor.ExecutePythonCode("/usr/bin/python3", "print('Hello, world!')");
Console.WriteLine($"Output: {result.output}");
Console.WriteLine($"Error: {result.error}");
}
}
Example
Here is a complete example demonstrating how to use both the PythonCodeValidator
and PythonExecutor
classes:
using System;
using System.Threading.Tasks;
using PythonExecutorLibrary;
class Program
{
static async Task Main()
{
// Validate Python code
string code1 = "import os\nprint('Hello, world!')";
string code2 = "def add(a, b):\n return a + b";
bool result1 = PythonCodeValidator.ContainsImportOrPrint(code1); // Returns true
bool result2 = PythonCodeValidator.ContainsImportOrPrint(code2); // Returns false
Console.WriteLine($"Code 1 contains 'import' or 'print': {result1}");
Console.WriteLine($"Code 2 contains 'import' or 'print': {result2}");
// Execute Python code asynchronously
var executor = new PythonExecutor(5);
var asyncResult = await executor.ExecutePythonCodeAsync("/usr/bin/python3", "print('Hello, async world!')");
Console.WriteLine($"Async Output: {asyncResult.output}");
Console.WriteLine($"Async Error: {asyncResult.error}");
// Execute multiple Python code snippets asynchronously
string[] scripts = { "print('Script 1')", "print('Script 2')" };
var multiResult = await executor.ExecuteMultiplePythonCodeAsync("/usr/bin/python3", scripts);
foreach (var output in multiResult.output)
{
Console.WriteLine($"Multi Output: {output}");
}
Console.WriteLine($"Multi Error: {multiResult.error}");
// Execute Python code synchronously
var syncResult = executor.ExecutePythonCode("/usr/bin/python3", "print('Hello, sync world!')");
Console.WriteLine($"Sync Output: {syncResult.output}");
Console.WriteLine($"Sync Error: {syncResult.error}");
}
}
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net7.0 is compatible. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net7.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
Added Async Methods, killing child process, package manager