簡體   English   中英

無法從 c# 將帶有空格的 arguments 傳遞給 python 腳本

[英]Not able to pass arguments with spaces to python script from c#

我正在使用 ProcessInfoStart 方法從 c# 調用 python 腳本。 作為參數,它接收 JSON 並輸入到 python 腳本。

它工作正常,我們通過 JSON 沒有任何空格,但如果有任何空格,則原始 JSON 被分割到空格並作為參數傳遞,rest 被忽略

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 腳本接受 arguments

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

有沒有辦法可以將帶有空格的 jRequest 傳遞給python腳本。

Python 腳本參數可以用單引號括起來,以便讀取包括空格在內的整個字符串

嘗試將JSON 字符串單引號括起來

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM