0

I'm trying to run a python script from a C# console app, the script is a simple CLI application. The problem is that when I run the console application, the output terminal does not show me any result returned from python script.

Python Script:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('FirstName')
parser.add_argument('LastName')

args = parser.parse_args()
first_name = args.FirstName
last_name = args.LastName

print(f"{first_name} {last_name}")

C# Code

namespace CS_PythonTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
        var psi = new ProcessStartInfo();
        psi.FileName = @"\python.exe";
        var script = "\pythonScript.py";

        psi.Arguments = $"{script}";
    
        psi.UseShellExecute = false;
        psi.CreateNoWindow= true;
        psi.RedirectStandardOutput= true;
        psi.RedirectStandardError= true;

        var errors = "";
        var results = "";

        using (var process = Process.Start(psi)) {
            errors = process.StandardError.ReadToEnd();
            results= process.StandardOutput.ReadToEnd();
        }

        Console.WriteLine(results);


        }
    }
}
  • Does this answer your question? [How do I run a Python script from C#?](https://stackoverflow.com/questions/11779143/how-do-i-run-a-python-script-from-c) – ThisQRequiresASpecialist Jan 25 '23 at 08:16
  • The code you've provided doesn't compile, due to `"\pythonScript.py"` - obviously that's easy to fix, but it does make me wonder what *other* aspects of the code you're running aren't actually as shown. (And are both `python.exe` and the python script itself in your root directory?) – Jon Skeet Jan 25 '23 at 08:19
  • Does this even run? The path arguments are both wrong. Both have an invalid backslash at the start. – Panagiotis Kanavos Jan 25 '23 at 08:20
  • The python script is in the root directory, but the 'python.exe' is not –  Jan 25 '23 at 08:26
  • 1
    @PanagiotisKanavos Most likely not but this is a duplicate and can easily be solved from the link I've provided above. It uses the exact same logic. There is a lot of nice detailed questions asked in there and good answers. – ThisQRequiresASpecialist Jan 25 '23 at 08:26
  • Shouldn't you pass these two arguments FirstName LastName aswell to your script? LIke `psi.Arguments = $"{script} John Doe";`? – lidqy Jan 25 '23 at 08:38
  • @CezarMarcu you aren't specifying the root directory, you're using an invalid escape sequence. A drive's root isn't `\\` anyway. – Panagiotis Kanavos Jan 25 '23 at 08:45
  • Have you checked the exit code and the `errors` string? – shingo Jan 25 '23 at 09:54

0 Answers0