0

Apologies for asking a question that's been asked so many times before, but I'm really suck.

I'm trying start a Python process from C#. I want to pass data from my C# program to a Python script, perform some IO in the Python script (it will be SFTP operations, but for simplicity's sake for now I am just returning text), and return the output to C#.

I have tried doing this with IronPython, but the Python library I will be using (Paramiko) is not supported. I have also attempted some version of this with PythonNet with no luck. I would like to stick to using C# processes for now. I know it's possible based on other posts I've seen on here, but I really can't figure out what I've got wrong.

The final C# program needs to be a class library. But for now as I test, I've configured the output type as Windows Application in order to get output in the debug window (Right click on class -> Application -> general -> output type -> Windows Application). The program has been set as the Startup Project.

When I run the code, the debugging window and tools pop up for a second, making me think it does call the script, but I don't get any output redirected to the debug window. At the end, it reads:

The program '[38860] ExecuteProcess.exe' has exited with code 0 (0x0).

C# code

the following code is based on this: How do I run a Python script from C#?

using System.Diagnostics;

namespace ExecuteProcess
{
    public class Class1
    {
        static void Main(string[] args)
        {
            string pythonExe = @"absolute_path_to_python.exe";
            string scriptDir = @"absolute_path_to_script_to_be_called_in_solution";
            string scriptArgs = "Hello World";

            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = pythonExe;
            start.Arguments = string.Format("{0} {1}", scriptDir, scriptArgs);
            start.UseShellExecute = false;
            start.CreateNoWindow = true;
            start.RedirectStandardOutput = true;
            start.RedirectStandardError = true;

            using (Process process = Process.Start(start))
            {
                using (StreamReader reader = process.StandardOutput)
                {
                    process.WaitForExit();
                    string result = reader.ReadToEnd();
                    Debug.WriteLine(result);
                }
            }
        }
    }

Python Code

print("In python script")

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("params", type='str', store=True)
args = parser.parse_args()


def func(params):
  print(args.params)
  return(args.params)

func(args.params)

I appreciate any input/help I can get. Thanks for reading, cheers.

InSync
  • 4,851
  • 4
  • 8
  • 30
eli7
  • 3
  • 1
  • Is the program running in debug mode? Have you tried to read the stderr? Which IDE are you using? If it's visual studio, what is the debugging window and tools? – shingo May 06 '23 at 04:27
  • @shingo Yes, running in debug mode. And if by stderr you mean any errors I get after I run this, I don't get any. I'm using visual studio yes. When the debug window appears, once it's done running, a bunch of messages appear saying how a bunch of .dlls were loaded and that the code executed with a code 0. – eli7 May 07 '23 at 18:04

1 Answers1

0

I used Console application and almost same code that in answer that you used.

static void Main(string[] args)
    {
        //My path to script file
        var scriptFile = "D:\\bf\\TestPython.py";
        //Comand line arguments (string "Hello World" in this case)
        var scriptArgs = "\"Hello World\"";
        ProcessStartInfo start = new ProcessStartInfo();
        //Path to python console
        start.FileName = "C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python311\\python.exe";
        start.Arguments = string.Format("{0} {1}", scriptFile, scriptArgs);
        start.UseShellExecute = false;
        start.RedirectStandardOutput = true;
        using (Process process = Process.Start(start))
        {
            using (StreamReader reader = process.StandardOutput)
            {
                string result = reader.ReadToEnd();
                Console.Write(result);
            }
        }
        Console.ReadKey();
    }

And i also corrected py script a bit:

print("In python script")

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("params", type=str)
args = parser.parse_args()

def func(params):
  print(args.params)
  return(args.params)

func(args.params)

I suggest you to try run this code in cnosole application too.

  • Unfortunately I can't use a console app for this. It's for work and because of how the code needs to interact with everything else it needs to be in a C# class library. – eli7 May 07 '23 at 18:00
  • *Making these code changes however gets the code to partially work. The print statement 'In python script' works, but not the function call that says 'hello world' – eli7 May 07 '23 at 18:14
  • Tested it in Windows Forms app, but whitout `Console.Write` and `Console.ReadKey` functions, and with additon to py script, to wite argument to .txt file. Just called this code from class method on button click event, worked fine. Perhaps you have some errors in your script? – Артем Павлов May 07 '23 at 18:28
  • Yes, oh man I included quotes around 'str' when using parser.add_argument() like a goof. Since there was no error handling nothing came up in the output but that was it. Thank you so much! – eli7 May 07 '23 at 18:32