0

我正在使用 ProcessInfoStart 方法从 c# 调用 python 脚本。作为参数,它接收 JSON 并输入到 python 脚本。

它工作正常,我们传递 JSON 时没有任何空格,但如果有任何空格,则原始 JSON 被分割到空格并作为参数传递,其余部分被忽略

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 脚本

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

有没有办法可以将带有空格的jRequest传递给 python 脚本。

4

1 回答 1

0

Python 脚本参数可以用单引号括起来,以便读取包括空格在内的整个字符串

尝试将JSON 字符串单引号括起来

于 2020-07-20T10:25:19.583 回答