【问题标题】:Calling a Python script function from C# Form从 C# 窗体调用 Python 脚本函数
【发布时间】:2021-12-27 09:42:28
【问题描述】:

我正在尝试从 C# 表单调用特定 Python 文件的函数,但我认为 IronPython 由于使用了自定义库(Microsoft.Scripting.SyntaxErrorException: 'unexpected token'创建范围)。 IronPython 问题可以解决吗?或者有其他方法可以解决吗?

这是我正在尝试做的一个示例:

PythonScript:

import customLib

def functionA:
        print("Hello, world!")

def functionB:
        customFunc()
        print("Goodbye!")

自定义库:

def customFunc:
       //do something

C# 表单

//calls PythonScript.FunctionB only

【问题讨论】:

    标签: python c# winforms ironpython


    【解决方案1】:

    您可以使用Process 类来实现此目的,该类提供对本地和远程进程的访问,并使您能够启动和停止本地系统进程。

    试试这样的:

     private void run_script()
     {
    
            string fileName = @"C:\your_script.py";
    
            Process p = new Process();
            p.StartInfo = new ProcessStartInfo(@"C:\Python27\python.exe", fileName)
            {
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };
            p.Start();
    
            string output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
    
            Console.WriteLine(output);
    
            Console.ReadLine();
    
    }
    

    【讨论】:

    • 您好,感谢您的回答!请问如何使用Process 类只调用脚本中的一个函数而不是全部执行?
    • 好吧,为此我推荐使用IronPython (:
    • 我尝试使用它,但我认为在执行脚本中导入非本机库时会出现一些问题。这是真的还是我错过了什么?
    猜你喜欢
    • 1970-01-01
    • 2022-01-17
    • 2013-08-22
    • 2012-01-23
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多