0

I am calling python script from c# using ProcessInfoStart method. As an argument it receives JSON and is input to python script.

It works fine it we pass JSON without having any spaces but if there is any space then original JSON is splitted till space and passes as argument and rest ignored

public static bool ExecutePythonScript(string jRequest, string fileType)
{
    string pythonExePath = Convert.ToString(ConfigurationManager.AppSettings["PythonExe"]);
    bool bIsExecutionSuccess = true;
    try
    {
        var psi = new ProcessStartInfo();
        psi.FileName = pythonExePath;
        var script = @"C:Scripts\pdf-to-csv.py";

        psi.Arguments = $"\"{script}\" \"{jRequest}\"";

        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();
        }

        if (!string.IsNullOrEmpty(errors))
            bIsExecutionSuccess = false;
    }
    catch(Exception ex)
    {
        bIsExecutionSuccess = false;
    }
    return bIsExecutionSuccess;
}

Python script to accept arguments

input_params = sys.argv[1]
input_params = input_params.replace("'",'"')
data_params = json.loads(input_params)

Is there a way i can pass jRequest with spaces to python script.

Ronak
  • 187
  • 2
  • 17

1 Answers1

0

Python script parameters can be wrapped in single quotes in order to read the whole string including spaces.

Try wrapping the JSON string in single quotes.

Ali Rida
  • 336
  • 2
  • 10
  • Is this the way ? psi.Arguments = $"\"{script}\" \'\"{jRequest}\"\'". That is actually not working for me, i am getting error. – Ronak Jul 20 '20 at 13:07