Python
C#
Interoperability
Programming
Scripting

How do I run a Python script from C?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In many .NET applications, the practical version of this problem is launching a Python script from C#. That is useful when a desktop tool or web service is mostly written in .NET but needs Python for data science code, image processing, or reuse of existing automation.

Starting Python as a Child Process

The simplest integration is to run the Python interpreter as an external process. In C#, the standard tool for that is System.Diagnostics.Process. This keeps the boundary clean: C# starts Python, passes arguments, reads output, and checks the exit code.

csharp
1using System;
2using System.Diagnostics;
3
4class Program
5{
6    static void Main()
7    {
8        var startInfo = new ProcessStartInfo
9        {
10            FileName = "python",
11            Arguments = "scripts/report.py input.txt",
12            RedirectStandardOutput = true,
13            RedirectStandardError = true,
14            UseShellExecute = false,
15            CreateNoWindow = true
16        };
17
18        using var process = new Process();
19        process.StartInfo = startInfo;
20        process.Start();
21
22        string output = process.StandardOutput.ReadToEnd();
23        string error = process.StandardError.ReadToEnd();
24        process.WaitForExit();
25
26        Console.WriteLine($"Exit code: {process.ExitCode}");
27        Console.WriteLine(output);
28
29        if (process.ExitCode != 0)
30        {
31            Console.Error.WriteLine(error);
32        }
33    }
34}

This pattern is reliable because it does not require embedding the Python runtime into your application. It also mirrors how you would run the script from a terminal, which makes debugging easier.

Passing Data In and Getting Data Out

For small inputs, command line arguments are enough. For larger inputs, writing to standard input or exchanging JSON through files is usually easier to maintain. Standard output is a good channel for structured machine-readable data, especially if the Python script prints JSON and nothing else.

Here is a simple Python script that prints JSON:

python
1# scripts/report.py
2import json
3import sys
4
5filename = sys.argv[1]
6
7with open(filename, "r", encoding="utf-8") as f:
8    lines = f.readlines()
9
10result = {
11    "line_count": len(lines),
12    "non_empty": sum(1 for line in lines if line.strip())
13}
14
15print(json.dumps(result))

The C# side can then deserialize that output.

csharp
1using System.Text.Json;
2
3var stats = JsonSerializer.Deserialize<ReportStats>(output);
4Console.WriteLine(stats?.LineCount);
5
6public record ReportStats(int line_count, int non_empty)
7{
8    public int LineCount => line_count;
9    public int NonEmpty => non_empty;
10}

If you need two-way streaming communication, you can also enable RedirectStandardInput and write to process.StandardInput. That is useful for interactive scripts, but it increases complexity because both sides must agree on message boundaries.

Environment Setup Matters

The most common deployment problem is assuming python resolves to the correct interpreter everywhere. On one machine it may point to Python 3.11, on another to Python 3.9, and on another it may not exist at all. Production code is safer when it uses an explicit interpreter path from configuration.

csharp
FileName = @"C:\Python311\python.exe";
Arguments = @"scripts\report.py input.txt";

Virtual environments are also important. If the Python script depends on packages like pandas or numpy, make sure the chosen interpreter belongs to the environment where those packages are installed.

When to Use Another Integration Style

Starting an external process is ideal when Python does a self-contained job and returns a result. If you need frequent fine-grained calls into Python code, the process boundary can become expensive. In that case, embedding Python with a library such as pythonnet may be a better fit, but setup and deployment are more involved.

For many applications, process-based execution stays the best choice because it is simple, observable, and easy to recover from when the script fails.

Common Pitfalls

A frequent mistake is leaving UseShellExecute enabled while also trying to redirect output. Redirection only works when UseShellExecute is false.

Another issue is deadlock from reading output incorrectly. If a script writes a large amount to standard error and the parent never reads it, the child process can block. Redirect and consume both output streams when the script may emit useful diagnostics.

Path handling is another source of trouble. Relative paths depend on the current working directory of the C# process, not the location of the executable. If scripts or data files live in known locations, build absolute paths before starting the process.

Summary

  • The simplest way to run Python from a .NET application is System.Diagnostics.Process.
  • Redirect standard output and standard error so results and failures are visible.
  • Prefer JSON or files for structured data exchange.
  • Use an explicit interpreter path or a controlled virtual environment in production.
  • Choose embedded Python only when repeated cross-language calls justify the added complexity.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.