Executing Python Code in C# using CodeInterpreterThoughts
Introduction
In the world of software development, it is common to work with multiple programming languages and frameworks. Sometimes, it becomes necessary to execute code written in one programming language from another. In this blog post, we will explore how to execute Python code in C# using the `CodeInterpreterThoughts` class.
Problem Statement
The `CodeInterpreterThoughts` class provides a way to execute Python code against a specific version of Python as well as with specific PIP package requirements. It takes the Python version, PIP dependencies, Conda dependencies, and the Python code to execute as input parameters. The class provides a method called `InvokeAsync` which executes the Python code and returns the response.
Code Explanation
Let’s take a closer look at the code and understand how it works.
Dependencies
The `CodeInterpreterThoughts` class has a dependency on the `FrostAura.Libraries.Core.Extensions.Validation` and `Microsoft.Extensions.Logging` namespaces.
using FrostAura.Libraries.Core.Extensions.Validation;
using Microsoft.Extensions.Logging;Class Structure
The `CodeInterpreterThoughts` class is a derived class from the `BaseThought` class. It contains an overloaded constructor that takes an instance of the `ILogger<CodeInterpreterThoughts>` class as a parameter.
public class CodeInterpreterThoughts : BaseThought
{
public CodeInterpreterThoughts(ILogger<CodeInterpreterThoughts> logger)
: base(logger)
{ }
}Execute Python Code
The `InvokeAsync` method is responsible for executing the Python code. It takes the Python version, PIP dependencies, Conda dependencies, and the Python code as input parameters. It also has an optional cancellation token parameter.
public async Task<string> InvokeAsync(
string pythonVersion,
string pipDependencies,
string condaDependencies,
string code,
CancellationToken token = default)
{
// Code execution logic
}The method first validates the input parameters and ensures that the Python code contains a function called `main` that accepts zero arguments and returns a string.
if (!code
.ThrowIfNullOrWhitespace(nameof(code))
.Contains("def main()")) throw new ArgumentException("The code block is required to contain a function called 'main' (def main()) that accepts zero arguments and returns a string.", nameof(code));Next, the method calls the `EnsurePythonEnvironmentAndGetPathAsync` method to create a Python environment if it does not already exist and retrieves the full Python process path.
var pythonExecutablePath = await EnsurePythonEnvironmentAndGetPathAsync(
pythonVersion.ThrowIfNullOrWhitespace(nameof(pythonVersion)),
pipDependencies.Split(' ').ToList(),
condaDependencies.Split(' ').ToList(),
token);The method then constructs the executable code by wrapping the Python code in a function called `main` and printing the output.
var outputIndicator = "OUTPUT";
var executableCode = $@"
{code}
print('{outputIndicator}>>>' + main() + '<<<{outputIndicator}')
";After that, the method calls the `ExecutePythonProcessAsync` method to execute the Python code and captures the response.
var response = await ExecutePythonProcessAsync(pythonExecutablePath, executableCode, token);Finally, the method normalizes the response by removing the output indicator and returns it.
var normalizedResponse = response
.Split($"{outputIndicator}>>>")
.Last()
.Split($"<<<{outputIndicator}")
.First();
return normalizedResponse;Create Python Environment
The `EnsurePythonEnvironmentAndGetPathAsync` method is responsible for creating a Python environment given a specific Python version and dependencies if it does not already exist. It takes the Python version, PIP dependencies, Conda dependencies, and a cancellation token as input parameters.
private async Task<string> EnsurePythonEnvironmentAndGetPathAsync(
string pythonVersion,
List<string> pipDependencies,
List<string> condaDependencies,
CancellationToken token)
{
// Python environment creation logic
}The method generates a unique hash for the given Python version and dependencies.
var environmentName = GetPythonEnvironmentHash(pythonVersion, pipDependencies, condaDependencies);It constructs the environment path and the Python executable path.
var environmentPath = $"envs/{environmentName}";
var pythonExecutablePath = $"{environmentPath}/bin/python";If the environment does not exist, the method provisions a new Conda environment and installs the Conda and PIP dependencies.
if (!Directory.Exists(environmentPath))
{
// Environment provisioning logic
}If the environment already exists, the method simply logs a message.
else
{
Console.WriteLine($"An environment with the required Python version and dependencies already exists. Using it ({environmentPath}).");
}
return pythonExecutablePath;Get Dean Martin’s stories in your inbox
Join Medium for free to get updates from this writer.
Generate Python Environment Hash
The `GetPythonEnvironmentHash` method generates a hash for a given Python version and dependencies. It takes the Python version, PIP dependencies, and Conda dependencies as input parameters and returns a hash string.
private string GetPythonEnvironmentHash(string pythonVersion, List<string> pipDependencies, List<string> condaDependencies)
{
// Hash generation logic
}The method combines the Python version, PIP dependencies, and Conda dependencies into a single string.
var sb = new StringBuilder();
foreach (string dep in pipDependencies.Order())
{
sb.Append(dep);
}
foreach (string dep in condaDependencies.Order())
{
sb.Append(dep);
}It computes the SHA256 hash of the input string and converts it to a hexadecimal string.
var data = SHA256
.Create()
.ComputeHash(Encoding.UTF8.GetBytes($"{pythonVersion}_{sb}"));
var sBuilder = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
return sBuilder.ToString();Execute Terminal Command
The `ExecuteProcessAsync` method is responsible for executing any terminal command silently and returning the stringified response. It takes the file name (process path), command, and a cancellation token as input parameters.
private async Task<string> ExecuteProcessAsync(string fileName, string command, CancellationToken token)
{
// Process execution logic
}The method creates a new `Process` instance and sets the file name and command arguments.
var process = new Process();
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = $"/c {fileName} {command}";
}
else
{
if (fileName == "conda" && !process.StartInfo.Environment["PATH"].Contains("miniconda3"))
{
fileName = $"~/miniconda3/bin/{fileName}";
}
process.StartInfo.FileName = "/bin/zsh";
process.StartInfo.Arguments = $"-c \"{fileName} {command}\"";
}The method starts the process, reads the output and error streams, and waits for the process to exit.
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.Start();
var output = await process.StandardOutput.ReadToEndAsync();
var error = await process.StandardError.ReadToEndAsync();
await process.WaitForExitAsync();If the process exits with a non-zero exit code, the method throws an exception with the error message.
if (process.ExitCode != 0)
{
throw new ApplicationException($"An error occured during the execution of the Python code (see the inner exception).{Environment.NewLine}{Environment.NewLine}{command}", new Exception(error));
}The method returns the output.
return output;Execute Python Code in Process
The `ExecutePythonProcessAsync` method is responsible for executing any terminal command silently and returning the stringified response. It takes the file name (process path), code, and a cancellation token as input parameters.
private async Task<string> ExecutePythonProcessAsync(string fileName, string code, CancellationToken token)
{
// Python process execution logic
}The method creates a new `Process` instance and writes the code to a temporary script file.
var process = new Process();
var tempScriptFilePath = $"{Guid.NewGuid()}.py";
await File.WriteAllTextAsync(tempScriptFilePath, code, token);The method sets the file name and script file path as the process arguments.
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = $"-c \"{fileName} {tempScriptFilePath}\"";
}
else
{
if (fileName == "conda" && !process.StartInfo.Environment["PATH"].Contains("miniconda3"))
{
fileName = $"~/miniconda3/bin/{fileName}";
}
process.StartInfo.FileName = "/bin/zsh";
process.StartInfo.Arguments = $"-c \"{fileName} {tempScriptFilePath}\"";
}The method starts the process, reads the output and error streams, and waits for the process to exit.
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.Start();
var output = await process.StandardOutput.ReadToEndAsync();
var error = await process.StandardError.ReadToEndAsync();
await process.WaitForExitAsync();If the process exits with a non-zero exit code, the method throws an exception with the error message.
if (process.ExitCode != 0)
{
throw new ApplicationException($"An error occured during the execution of the Python code (see the inner exception).{Environment.NewLine}{Environment.NewLine}{code}", new Exception(error));
}The method returns the output.
return output;Conclusion
In this blog post, we explored how to execute Python code in C# using the `CodeInterpreterThoughts` class. We learned about the different methods and their responsibilities. By leveraging this code, developers can seamlessly execute Python code within their C# applications, opening up possibilities for integration and interoperability between the two programming languages.
Disclaimer
The above article was completely autonomously generated by an AI pipeline that I have coded as well as the code interpreter code that I wrote prior, so please excuse any oddities. We will improve over time. :)
Links & References
- fa.libraries.dotnet/src/Semantic.Core/Thoughts/Cognitive/CodeInterpreterThoughts.cs at master · faGH/fa.libraries.dotnet (github.com)
- fa.libraries.dotnet/src/Semantic.Core.Tests/Thoughts/Cognitive/CodeInterpreterThoughtsTests.cs at master · faGH/fa.libraries.dotnet (github.com)
- NuGet Gallery | FrostAura.Libraries.Intelligence.Semantic.Core 1.0.1




