【问题标题】:Run python Script(having input()) exe form C#运行python脚本(输入())exe表单C#
【发布时间】:2021-11-02 08:13:40
【问题描述】:

我有具有输入命令的 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();

请提出建议。

【问题讨论】:

  • 您是否以管理员身份运行了 C# exe? (假设您在 Windows 机器上)& 当您通过 cmd 手动操作时它是否有效?
  • 是的。目前我处于调试模式。还尝试从调试文件夹以管理员身份以 C# exe 运行。
  • 你能通过cmd手动运行吗?
  • 有没有其他方法可以解决这个问题?

标签: c# python .net


【解决方案1】:
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 模块一无所知,所以我只是复制并编辑了您的代码

【讨论】:

  • 感谢您的回复。我尝试了您的 cmets,但不知何故 python 脚本无法在 .net 应用程序中运行。
  • 您是否更改了两者或一项一项尝试,您将一项一项尝试。我的意思是如果更改 python 代码不起作用更改 c# 代码
  • 你检查 python 是否在路径中?你遇到了什么错误?
  • 您能帮我解决我的新问题吗? stackoverflow.com/questions/69754542/…
【解决方案2】:

在 C# 代码中运行 python 代码:

class Hello:
    def say_hello():
       print('hello')
static void Main(string[] args)
{
    //instance of python engine
    var engine = Python.CreateEngine();
    //reading code from file
    var source = engine.CreateScriptSourceFromFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PythonSampleIronPython.py"));
    var scope = engine.CreateScope();
    //executing script in scope
    source.Execute(scope);
    var helloClass= scope.GetVariable("Hello");
    //initializing class
    var helloInstance= engine.Operations.CreateInstance(helloClass);
    Console.WriteLine("From Iron Python");
    Console.WriteLine(helloInstance.say_hello());
}

在 c# 代码中运行 python .exe:

string args = @"D:\appFolder\config.json";
string path = @"D:\appFolder\filePathExe.exe";
Process proc = new Process();
ProcessStartInfo si = new ProcessStartInfo(path, args);
si.WindowStyle = ProcessWindowStyle.Normal;
si.WorkingDirectory = @"D:\appFolder";
si.Verb = "runas";             // UAC elevation required.
si.UseShellExecute = true;     // Required for UAC elevation.
proc.StartInfo = si;
proc.Start();
proc.WaitForExit();

【讨论】:

【解决方案3】:

如果你在脚本中输入的输入提示("Give document directory:")被打印出来,那么这意味着python脚本在C#代码内部正常运行。

但是当脚本等待来自标准输入的输入时,您将参数传递给脚本,这是完全不同的事情。要解决这个问题,您应该:

替换这个:

strDocDir = input("Give document directory:")

为此:

import sys
if len(sys.argv) > 1:
    strDocDir = sys.argv[1]
else:
    strDocDir = input("Give document directory:")    

然后它将使用传递的参数(如果有)。 如果没有传递参数,那么它将要求输入。 这样,当没有传递参数时,脚本仍然可以像旧脚本一样工作,但也可以与 C# 代码一起使用。

另一方面,如果输入提示没有打印出来,那就意味着脚本由于某种原因没有运行。

在这种情况下,首先尝试直接从控制台运行 python 编译脚本(.exe)以检查它是否有效。

【讨论】:

    猜你喜欢
    • 2020-09-22
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-02
    • 2022-01-04
    • 2019-07-14
    • 2023-03-10
    相关资源
    最近更新 更多