运行python脚本(具有input())exe形式C#

时间:2018-06-05 09:41:46

标签: c# python .net

我有python脚本有输入命令,即从用户输入(目录)。使用PyInstaller我生成了该脚本的exe。现在我想通过给出输入参数来消耗C#中的这个exe。但不知何故,即使在从C#发出参数之后,也没有采取并弹出Python exe命令提示符。

Python代码:

def CreateCSVFile(CSVDirectory):
    try:
        file_path = os.path.join(CSVDirectory, 'ExportResult_Stamp.csv')
        ## delete only if file exists ##
        if os.path.exists(file_path):
            os.remove(file_path)
        # Create column names as required
        row = ['FileName', 'Document123','abc','xyz','zzz']
        with open(file_path, 'w+') as csvFile:
            writer = csv.writer(csvFile)
            writer.writerow(row)
        csvFile.close()
    except Exception as e:
        print(str("Exception occurs:"+ e))

strDocDir = input("Give document directory:")
#print(strDocDir)
if os.path.exists(os.path.dirname(strDocDir)):
    CreateCSVFile(strDocDir)
else:   
    warnings.warn("Provided directory doesn't exist:" + strDocDir)

C#代码:

string strCurrentPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
                ProcessStartInfo startInfo = new ProcessStartInfo(string.Concat(strCurrentPath, "\\Test\\", "CSV.exe"));
                startInfo.Arguments = @"C:\Pankaj\Office\ML\Projects\Stampdocuments\DDR041";
                startInfo.UseShellExecute = true;                
                var process = System.Diagnostics.Process.Start(startInfo);
                process.WaitForExit();

请建议。

1 个答案:

答案 0 :(得分:0)

import sys

.....

strDocDir = sys.argv[1]

改变它是因为你传递的参数没有输入任何东西,如果你想使用输入仍然你应该检查出Repeatably Feeding Input to a Process' Standard Input(答案是因为新行还需要python)

 var process = new Process
                          {
                              StartInfo =
                                  {
                                      FileName = string.Concat(strCurrentPath, "\\Test\\", "CSV.exe"),
                                      RedirectStandardInput = true,
                                      RedirectStandardError = true,
                                      RedirectStandardOutput = true,
                                      UseShellExecute = false,
                                      CreateNoWindow = true,
                                      ErrorDialog = false
                                  }
                          };


        process.EnableRaisingEvents = false;

        process.Start();

        var standardInput = process.StandardInput;
        standardInput.AutoFlush = true;
        var standardOutput = process.StandardOutput;
        var standardError = process.StandardError;

        standardInput.Write(@"C:\Pankaj\Office\ML\Projects\Stampdocuments\DDR041");
        standardInput.Close(); // <-- output doesn't arrive before after this line
        var outputData = standardOutput.ReadLine();

        process.Close();
        process.Dispose();

顺便说一下我对c#的Process模块一无所知,所以我只是为你的代码复制和编辑了