【问题标题】:Windows Universal Apps: Call python method from C# [closed]Windows 通用应用程序:从 C# 调用 python 方法 [关闭]
【发布时间】:2016-01-04 18:18:39
【问题描述】:

我有一个 .py 文件我想调用并获取它在我的应用程序中返回的值。

我的主要目的是在基于 C# 的通用应用程序中使用 scikit-learn 进行机器学习,我将如何实现?

【问题讨论】:

  • 到目前为止您尝试过什么?我们恳请您先尝试自己解决问题,然后再尝试为您提供帮助。
  • @Torxed 到目前为止我一直在使用 Ironpython,但它不包括 scikit-learn 所以我不得不放弃这条路

标签: c# python scikit-learn uwp


【解决方案1】:

在 UWP 中,您的选择非常有限。通用应用程序在沙箱中运行,并且在与经典桌面应用程序(例如 Python)交互方面受到限制,这会阻止您使用本地 Python 安装简单地“shell 执行”您的脚本。

有一种方法可以在 Windows 8.1 WinRT 中使用brokered components,但需要侧载应用程序;它不适用于从商店安装的应用程序。当然,它需要 Windows 的桌面版本,也不能在 Windows Phone 上运行。此外,我没有看到与 Windows 10 UWP 相关的任何提及,我严重怀疑它是否仍然有效。

您最好的选择可能是尝试UWP version of CPython。我从未使用过它,我不知道它所处的状态,也不知道要让 scikit-learn 在其中工作需要付出多少努力。但是,如果您希望您的应用程序在多个平台(桌面、移动、物联网......)上运行,我不知道还有其他选择。

另一方面,如果你只针对桌面,我建议你放弃使用 UWP 并创建一个经典的桌面应用程序。这将允许您通过调用本地安装的版本或将其嵌入到您的应用程序中来不受任何限制地使用标准 CPython 版本。

【讨论】:

  • 感谢您的回复,我考虑切换到 WPF,但它不包含 Microsoft Band 的 SDK。
  • 我正在考虑使用 Azure 机器学习,因为它允许我包含 Python 脚本,你怎么看?
  • 我对Microsoft Band SDK一点也不熟悉,但是如果它依赖于UWP API,也许你可以在UWP for Desktop NuGet package的帮助下使用它。它允许您从桌面应用程序访问 UWP API
  • 我没有使用 Azure 机器学习的经验,我只参加过一次关于它的介绍性会议。如果它适合您的需要,这可能是有道理的,尽管这听起来有点矫枉过正。
【解决方案2】:

您可以使用独立应用代理。正如 Damir Arh 所说,这种方法不能用于通过商店分发您的应用程序。 主要思想是为代理注册一个自定义扩展并通过执行帮助文件来启动它。

代理:

static class Program
{
    const string ProxyExtension = ".python-proxy";
    const string ResultExtension = ".python-proxy-result";

    [STAThread]
    static void Main(params string[] args)
    {
        if (args.Length != 1)
            return;

        if ("install".Equals(args[0], StringComparison.Ordinal))
        {
            var path = Application.ExecutablePath;
            SetAssociation(ProxyExtension, "PythonProxy", path, "Python Proxy");
        }
        else
        {
            var path = args[0];
            if (!File.Exists(path))
                return;
            var serviceExt = Path.GetExtension(path);
            if (!ProxyExtension.Equals(serviceExt, StringComparison.OrdinalIgnoreCase))
                return;
            path = Path.Combine(Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path).TrimEnd());
            var ext = Path.GetExtension(path);
            if (!".py".Equals(ext, StringComparison.OrdinalIgnoreCase))
                return;

            var start = new ProcessStartInfo
            {
                FileName = "python.exe",
                Arguments = '"' + path + '"',
                UseShellExecute = false,
                RedirectStandardOutput = true,
                CreateNoWindow = true,
            };

            using (var process = Process.Start(start))
            {
                using (var reader = process.StandardOutput)
                {
                    var result = reader.ReadToEnd();
                    var output = path + ResultExtension;
                    using (var mutex = new Mutex(true, "PythonProxy Mutex"))
                    {
                        File.WriteAllText(output, result);
                    }
                }
            }
        }
    }

    public static void SetAssociation(string ext, string name, string openWithPath, string description)
    {
        using (var key = Registry.ClassesRoot.CreateSubKey(ext))
        {
            if (key == null)
                return;

            key.SetValue("", name);
        }

        using (var key = Registry.ClassesRoot.CreateSubKey(name))
        {
            if (key == null)
                return;

            key.SetValue("", description);

            using (var shellKey = key.CreateSubKey("shell"))
            {
                if (shellKey == null)
                    return;

                using (var openKey = shellKey.CreateSubKey("open"))
                {
                    if (openKey == null)
                        return;

                    using (var commandKey = openKey.CreateSubKey("command"))
                    {
                        if (commandKey == null)
                            return;

                        commandKey.SetValue("", $"\"{openWithPath}\" \"%1\"");
                    }
                }
            }
        }

        using (var key = Registry.CurrentUser.OpenSubKey($@"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{ext}"))
        {
            if (key != null)
                key.DeleteSubKey("UserChoice", false);
        }

        Native.SHChangeNotify(Native.SHCNE_ASSOCCHANGED, Native.SHCNF_IDLIST, IntPtr.Zero, IntPtr.Zero);
    }

    class Native
    {
        public const uint SHCNE_ASSOCCHANGED = 0x08000000;
        public const uint SHCNF_IDLIST = 0x0000;

        [DllImport("shell32.dll")]
        public static extern void SHChangeNotify(uint wEventId, uint uFlags, IntPtr dwItem1, IntPtr dwItem2);
    }
}

通用应用:

public async void Fun()
{
    var local = ApplicationData.Current.LocalFolder;

    var scriptFile = await local.CreateFileAsync("script.py", CreationCollisionOption.ReplaceExisting);
    using (var stream = await scriptFile.OpenStreamForWriteAsync())
    using (var writer = new StreamWriter(stream))
    {
        await writer.WriteLineAsync(@"print ""Hello, World!""");
    }

    var proxyFile = await local.CreateFileAsync("script.py.python-proxy", CreationCollisionOption.ReplaceExisting);
    await Launcher.LaunchFileAsync(proxyFile);

    var resultPath = "script.py.python-proxy-result";
    var counter = 0;
    IStorageItem resultFile = null;
    while (resultFile == null)
    {
        if (counter != 0)
        {
            if (counter++ > 5)
                throw new Exception();
            await Task.Delay(250);
        }
        resultFile = await local.TryGetItemAsync(resultPath);
    }

    try
    {
        using (var mutex = new Mutex(true, "PythonProxy Mutex")) { }
    }
    catch (AbandonedMutexException) { }

    using (var stream = await local.OpenStreamForReadAsync(resultPath))
    using (var reader = new StreamReader(stream))
    {
        var content = await reader.ReadToEndAsync();
        var dialog = new MessageDialog(content);
        await dialog.ShowAsync();
    }

    await scriptFile.DeleteAsync();
    await proxyFile.DeleteAsync();
    await resultFile.DeleteAsync();
}

【讨论】:

    【解决方案3】:

    我相信如果你使用类似的东西 (How to print out the value that subprocess prints with C#?) 来运行你的 python 脚本并捕获标准输出,你应该能够实现所需的功能

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-04
      • 1970-01-01
      • 2014-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多