Run a Python Script in a Virtual Environment Using .NET

How to run a python script inside a venv using .NET? First, let us create a new python venv in Windows.

python -m venv dotnet-venv

Then, we activate the virtual environment to do some testing.

# Use this command for command prompt
C:\> <venv>\Scripts\activate.bat
# Use this command for Powershell
PS C:\> <venv>\Scripts\Activate.ps1

After activated, you will able to see venv name on the left-hand side before the current path e.g. (dotnet-venv) PS C:\PythonProjects\dotnet-venv>.

We will install some packages in the venv, so the virtual environment has more packages than the system.

pip install pandas
pip install pyarrow

Write a python test code such as below and save it as py-dotnet-test.py:

# Import pandas
import pandas as pd

# Create a DataFrame with some data
df = pd.DataFrame({
    "name": ["Alice", "Bob", "Charlie"],
    "age": [25, 30, 35],
    "gender": ["F", "M", "M"]
})

# Write the DataFrame to a CSV file
df.to_csv("result.csv", sep=" ", encoding="utf-8", header=False, index=False)

Try executing it on venv, you should be able to see the result.csv on your directory.

To execute the python script in venv using .NET, just use the code below and point the execution path to venv python.exe.

string venvDir = @"C:\<venv>\dotnet-venv\";
ProcessStartInfo start = new ProcessStartInfo();
// Please note the python.exe must be the one inside venv, else you will get error such as ModuleNotFoundError: No module named 'pandas'
start.FileName = venvDir + @"Scripts\python.exe";
start.Arguments = venvDir + @"py-dotnet-test.py"; // Script parameters can be put at the end.
start.WorkingDirectory = venvDir;
// You can temp comment out the two lines below to see the running progress
start.WindowStyle = ProcessWindowStyle.Hidden;
start.CreateNoWindow = true;

using (Process process = Process.Start(start))
{
	process.WaitForExit();
}

After you run the dotnet code, you should be able to see the result.csv in your directory :).

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.