使用PythonNet在Windows窗体应用程序中打开交互式pythonshell实例

2024-09-30 03:22:13 发布

您现在位置:Python中文网/ 问答频道 /正文

正如标题所说,我想在Windows窗体应用程序中为python启动一个交互式shell实例

.NET运行时:.NET Framework 4.7.2 Python版本:3.8.10 PythonNet版本:3.0

这是我的C#代码:

using System;
using System.Windows.Forms;
using Python.Runtime;


namespace PythonInteractiveGUI
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Runtime.PythonDLL = @"C:path\to\python38.dll";
            PythonEngine.Initialize();

            string command = System.IO.File.ReadAllText("script2.py");

            using (Py.GIL())
            {
                using (PyScope scope = Py.CreateScope())
                {
                    scope.Exec(command);
                }
            }
            PythonEngine.Shutdown();
        }
    }
}

我的Python代码位于script2.py中:

import code
variables = globals().copy()
variables.update(locals())
shell = code.InteractiveConsole(variables)
shell.interact()

上述操作会导致错误:

  HResult=0x80131500
  Message=input(): lost sys.stdin
  Source=Python.Runtime
  StackTrace:
<Cannot evaluate the exception stack trace>

我认为这与缺少可用的控制台窗口有关,但我不确定如何继续。当在控制台应用程序下使用相同的.NET Framework、python和Pythonnet版本时,这一点是有效的

谢谢

更新:2021年6月7日 我能够使用接受的以下答案添加控制台窗口:How do I show a console output/window in a forms application?

这导致了另一个问题,似乎证实了我的怀疑: PythonException


Tags: 代码版本应用程序netwindowsframeworkpublicvariables

热门问题