目录
使用C# Avalonia Gidon插件框架托管Python应用程序
在主Python环境中的Windows计算机上运行示例(没有Python虚拟环境)
主C#项目DockableAppImplantsDemo的代码
介绍
Python的优势
最近,我一直在用Python做很多工作。我的观点是,对于个人科学家和开发人员来说,Python是一种很棒的语言。它可能比任何其他语言或包具有更多的内置科学和绘图库,并且大多数广泛使用的Python库都是免费的。
Python被认为非常简单,科学家们喜欢这一点,因为他们希望专注于自己的专业领域,而不是花很多时间学习软件语言。
Python的另一个巨大优势是它是多平台的,在Windows,Linux和MacOS上的工作方式完全相同。
Python具有出色的交互式环境,允许在构建和调整Python程序时试验软件和数据。
Python是一种解释型语言,不需要编译。
Python的缺点
通用Python是一种解释型语言,因此非常慢。有一些版本的Python编译和运行速度要快得多,但没有多少版本在使用它们。我假设随着编译代码性能的提高,这些版本的编译时间变得越来越麻烦。
由于Python缺乏强类型,它的智能感知类似于JavaScript,并且比C#或Java等强类型语言差得多。正因为如此,Python库可能更难学习。
如上所述,Python是一种非常适合个人开发的语言,尽管它在团队开发,插件和关注点分离方面没有强大的功能。
使用C# Avalonia Gidon插件框架托管Python应用程序
Gidon MVVM插件框架已在 Gidon——基于Avalonia的MVVM Plugin IoC容器中进行了描述。在那篇文章中,我介绍了一种创建动态加载的C#插件的方法。
最近,我为Gidon添加了一个功能,使其能够托管作为独立Python进程运行的Python Windows。
Python Windows通过使用多平台Avalonia UniDock窗口停靠框架植入到C#中,该框架是Gidon的一部分。因此,Python Windows可以停靠或选项卡在一起,或者拉到单独的浮动窗口中。
各种Python和C#进程之间的通信是通过具有关注点分离的发布/订阅gRPC中继服务器中所述的RelayServer完成的,并由托管主Avalonia窗口的C#进程运行。
以下是具有三个植入Python Windows的Gidon示例的外观:
下面将详细介绍此示例的代码。
这些图的Python代码取自 matplotlib教程,并添加了 PySide6 代码以制作独立的窗口。
可以使用Python绘图的标题来重新排列它们,将它们中的一些拉到独立的浮动窗口中或将它们选项卡,例如:
在上图中,直方图与点图一起选项卡,而正弦曲线停靠在它们旁边。
本文中使用的软件
在C#方面,开源的Gidon MVVM插件包现在包含了植入Python窗口所需的所有其他内容。
作为Gidon的一部分,我使用Avalonia——一个开源的C#多平台版本的WPF来创建Shell的UI,Python窗口将被植入其中。
Gidon窗口对接功能由基于Avalonia的UniDock框架推动。
对于单个绘图,我使用Python matplotlib库与PySide6 Python UI库相结合。
对于不同进程之间的通信,我使用基于Grpc的中继服务器(它成为Gidon框架的一部分)。
示例代码位置
示例代码位于NP.Avalonia.Demos 代码库的 Gidon/DockableAppsDemo 文件夹下。
Visual Studio解决方案文件(包括C#和Python代码)位于DockableAppImplantsDemo.sln中的 Gidon/DockableAppsDemo/DockableAppImplantsDemo 文件夹中。
在Windows上运行示例代码
先决条件
若要在Windows上运行示例代码,需要满足以下先决条件:
- 具有Python功能的Visual Studio 2022。我使用专业版(不确定社区添加是否有效,但很可能——是的)。
- 您应该在Windows机器上安装最新的Python3和Pip3版本(Pip for Python用于安装Python包——类似于Nuget for C#)。
- 您应该有一个有效的互联网连接来安装C#和Python包。
示例代码结构
示例的代码由一个主C#项目DockableAppImplantsDemo——和应用程序解决方案文件夹下的四个Python项目组成:
- CommonPython
- DotPyMatPlot
- HistogramPlot
- SinusoidPyMatPlot
CommonPython仅当您想使用Python虚拟环境时才需要项目,如下所述。
其余的Python项目一对一对应于示例中的各种映射。
在主Python环境中的Windows计算机上运行示例(没有Python虚拟环境)
使用主Python环境运行示例(而不是创建特殊的虚拟环境)更容易,但它会将一些Python包添加到主Python环境中。
因此,如果您想保留您的主Python环境,请跳过此小节并转到下一个解释如何创建虚拟Python环境并将其用于示例的小节。
由于您使用的是主Python环境,请为每个Python项目选择它(如果您只有一个环境,Visual Studio应该已经为您完成了):
在其中一个项目中,例如DotPyMatPlot,左键单击主环境并选择从requirements.txt安装选项:
由于每个项目中的requirements.txt文件都是相同的,并且由于您要更新相同的全局可用环境,因此选择哪一个并不重要。
以下是内容或任何requirements.txt文件,列出了运行Python示例所需的所有包:
cycler==0.11.0
grpcio==1.51.3
kiwisolver==1.4.4
matplotlib==3.7.0
NP.Grpc.PythonMessages==0.99.2
NP.Grpc.PythonRelayInterfaces==0.99.2
numpy==1.24.2
packaging==23.0
Pillow==9.4.0
pip==22.3.1
protobuf==4.22.0
pyparsing==3.0.9
PySide6==6.4.2
PySide6-Addons==6.4.2
PySide6-Essentials==6.4.2
python-dateutil==2.8.2
setuptools==65.5.0
shiboken6==6.4.2
six==1.16.0
主要软件包包括:
- Matplotlib——用于创建情节
- Numpy——用于计算图的数据
- PySide6——用于构建UI窗口和(如果需要添加按钮和其他常见的UI控件)
- NP.Grpc.PythonRelayInterfaces——用于与中继服务器的通用通信机制
- NP.Grpc.PythonMessages——用于将窗口句柄传送到中继服务器的特定WindowInfo消息
安装Python包后,您可以检查各个Python项目是否运行,例如,在DotPyMatPlot上右键单击并选择调试>启动新实例:
应弹出包含相应绘图的Python应用程序:
Python应用程序检测到它是独立的(由于缺少命令行参数),并且不会尝试调用中继服务器,中继服务器是C#项目的一部分,并且在仅启动Python项目时未运行。
杀死Python程序(如果仍在运行)。
右键单击主项目DockableAppImplantsDemo,然后选择“重建”。
等待成功构建并运行主项目:
现在,您可以通过拖动图块,停靠图并按不同顺序使用选项卡来播放图块。
将虚拟环境用于Python项目
如果你不想修改你的主Python环境,你仍然可以在CommonPython项目中创建一个虚拟环境,调用env,激活它,从requirements.txt中安装包并且所有Python项目都会按名称env选择它。
注意,您必须创建一个专门称为env的虚拟环境,否则预定义的搜索路径将不起作用。如果您已经有一个全局可用的env环境并且不想更改它,则可以创建一个不同名称的虚拟环境,然后修改所有Python项目的搜索路径,例如
此外,您必须稍微修改每个项目的代码——特别是行:
sys.path.append(r'..\CommonPython\env\Lib\site-packages')
必须修改以指向正确的环境路径。
要在CommonPython项目下创建新环境,请右键单击其 Python 环境并选择添加环境:
在打开的对话框中,单击“在Python环境中查看”窗口,然后单击“创建”按钮:
您可能需要等待几秒钟,环境才会显示在项目的“Python环境”下。右键单击它并选择激活环境:
新环境应从requirements.txt自动填充,展开它以检查其包内容,如果未填充——右键单击它并选择从requirements.txt安装。
现在,您可以单独测试Python项目,并按照上一小节中所述生成和启动主C#项目DockableAppImplantsDemo。
代码解释
在这里,我将解释允许将Python应用程序嵌入到C# shell中的C#和Python代码。
主C#项目DockableAppImplantsDemo的代码
示例的主C#项目依赖于四个nuget包:
- NP.Avalonia.Gidon——主要依赖关系
- NP.Grpc.RelayClient——RelayServer客户端的实现
- NP.Grpc.RelayServer——RelayServer实现
- XamlNameReferenceGenerator——解析XAML代码所需的阿瓦隆尼亚文件
在上面列出的项目中,NP.Grpc.RelayClient和NP.Grpc.RelayServer作为插件安装(如创建和安装插件作为Nuget包中所述)。这意味着它们的实现代码对示例程序不可用,只有它们的接口由NP.Grpc.CommonRelayInterfaces包作为NP.Avalonia.Gidon包的一部分提供。
文件 App.axaml 包含(像往常一样)对跨应用程序共享的常见样式的引用:
<Application xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="DockableAppImplantsDemo.App">
<Application.Styles>
<StyleInclude Source="avares://Avalonia.Themes.Default/Accents/BaseLight.xaml"/>
<StyleInclude Source="avares://Avalonia.Themes.Default/DefaultTheme.xaml"/>
<StyleInclude Source="avares://NP.Avalonia.Visuals/Themes/CustomWindowStyles.axaml"/>
<StyleInclude Source="avares://NP.Avalonia.UniDock/Themes/DockStyles.axaml"/>
</Application.Styles>
</Application>
App.axaml.cs文件更有趣,因为它定义了从IoC提供的插件构建RelayServer和RelayClient对象的方法。它还创建观察类型对象的WindowHandleMatcher对象:
public class WindowInfo
{
long WindowHandle { get; }
string UniqueWindowHostId { get; }
}
来自Python程序。在用于将具有正确句柄的 Windows 插入其主机对象的MultiPlatformProcessInitInfoWithMatcher对象中提供了对WindowHandleMatcher的引用(正如我们在查看 MainWindow.axaml 文件时将解释的那样)。
以下是 App.axaml.cs 文件中记录的有趣部分:
public class App : Application
{
// IoC Container
private static IDependencyInjectionContainer<Enum> IoCContainer { get; }
// IRelayServer (provided so that we could shut it down when the program shuts down)
private static IRelayServer TheRelayServer { get; }
// IRelayClient used for getting WindowHandles from the python windows
// started in different processes
private static IRelayClient TheRelayClient { get; }
// Window handle matcher - matches the window handle with the unique
// window host id
public static WindowHandleMatcher TheWindowHandleMatcher { get; }
static App()
{
// create the container builder
IContainerBuilderWithMultiCells<Enum> containerBuilder =
new ContainerBuilder<Enum>();
// register a multicell that can container several different Enum values
// corresponding to the various topics of the RelayServer.
// Here we use only one topic - WindowInfoTopic the allows to publish
// and subscribe object of WindowInfo type
// (contained within NP.Gidon.Message package) that
// provide the WindowHandle (of type long) and UniqueWindowHostId
// (or type string)
containerBuilder.RegisterMultiCell(typeof(Enum), IoCKeys.Topics);
// provides an object for determining Grpc server host and port
// (in our simple case they are hardcoded to "localhost"
// and 5051 correspondingly)
containerBuilder.RegisterType<IGrpcConfig, GrpcConfig>();
// provides the topics MultiCell (only one topic WindowInfoTopic - in our case)
containerBuilder.RegisterAttributedStaticFactoryMethodsFromClass
(typeof(MessagesTopicsGetter));
// picks up the RelayServer and RelayClient implementations
// as plugins from Plugins/Services folder
containerBuilder.RegisterPluginsFromSubFolders("Plugins/Services");
// builds the IoC Container
IoCContainer = containerBuilder.Build();
// gets a reference to the Relay Server from the container
TheRelayServer = IoCContainer.Resolve<IRelayServer>();
// gets a reference to the RelayClient from the container
TheRelayClient = IoCContainer.Resolve<IRelayClient>();
// gets the WindowHandleMatcher - an object that observes the
// RelayServer from WindowInfo objects
// and fires events matching the UniqueWindowHostId and the
// WindowHandle every time
// such objects arrive
TheWindowHandleMatcher = new WindowHandleMatcher(TheRelayClient);
}
...
}
然而,真正的内容位于MainWindow.axaml文件中。它定义了一个简单的UniDock组,其中包含三个DockItems——每个图一个。顶部有两个停靠项,底部有一个停靠项。
要了解有关UniDock框架的更多信息,请阅读 UniDock——一种新的多平台UI Docking Framework.UniDock强大特性。
每个DockItems的内容都非常相似,仅用于调用不同的Python程序,所以我只解释其中之一:
<np:DockItem Header="Dot Plot" DockId="DockPlot">
<np:DockItemImplantedWindowHost x:Name="TheWindowHostContainer1"
Margin="2"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<np:DockItemImplantedWindowHost.ProcessInitInfo>
<np:MultiPlatformProcessInitInfoWithMatcher UniqueWindowHostId="DotPlot"
TheWindowHandleMatcher="{x:Static local:App.TheWindowHandleMatcher}">
<np:MultiPlatformProcessInitInfoWithMatcher.WindowsProcInitInfo>
<np:ProcessInitInfo ExePath="pythonw"
WorkingDir="../../../../Apps/DotPyMatPlot/" InsertIdx="1">
<np:ProcessInitInfo.Args>
<x:String>DotPyMatPlot.py</x:String>
</np:ProcessInitInfo.Args>
</np:ProcessInitInfo>
</np:MultiPlatformProcessInitInfoWithMatcher.WindowsProcInitInfo>
<np:MultiPlatformProcessInitInfoWithMatcher.LinuxProcInitInfo>
<np:ProcessInitInfo ExePath="python3"
WorkingDir="../../../../Apps/DotPyMatPlot/" InsertIdx="1">
<np:ProcessInitInfo.Args>
<x:String>DotPyMatPlot.py</x:String>
</np:ProcessInitInfo.Args>
</np:ProcessInitInfo>
</np:MultiPlatformProcessInitInfoWithMatcher.LinuxProcInitInfo>
</np:MultiPlatformProcessInitInfoWithMatcher>
</np:DockItemImplantedWindowHost.ProcessInitInfo>
</np:DockItemImplantedWindowHost>
</np:DockItem>
每个DockItem对象都包含一个DockItemImplantedWindowHost类型的对象,该对象通过其设置为包含MultiPlatformProcessInitInfoWithMatcher对象的ProcessInitInfo属性来处理与中继客户端的通信。后一个对象包含UniqueWindowHostId(对于应用程序应该是唯一的)和TheWindowHandleMatcher——包含对该WindowHandleMatcher对象的引用。
它还具有定义如何在相应操作系统上启动进程的几个属性。例如,WindowProcInitInfo指定如何在Windows上启动进程,而在Linux上启动——LinuxProcInitInfo。
例如,WindowProcInitInfo设置为:
<np:ProcessInitInfo ExePath="pythonw"
WorkingDir="../../../../Apps/DotPyMatPlot/" InsertIdx="1">
<np:ProcessInitInfo.Args>
<x:String>DotPyMatPlot.py</x:String>
</np:ProcessInitInfo.Args>
</np:ProcessInitInfo>
表示在Windows上启动python进程的命令是pythonw(这是可以在没有控制台的情况下启动python窗口的命令),Python进程中启动的文件夹是../../../../Apps/DotPyMatPlot/,唯一窗口主机ID插入索引1处,启动的Python程序是 DotPyMapPlot.py。
所以启动Python过程的总行是:
pythonw ../../../../Apps/DotPyMatPlot/DotPyMatPlot.py DotPlot
其中DotPlot是当前DockItem的唯一窗口主机ID。
记住,WindowHandleMatcher的static实例连接到我们的MultiPlatformProcessInitInfoWithMatcher对象,当一个WindowInfo对象从RelayServer到达(由Python进程发布给它)时,它将触发一个事件。
该MultiPlatformProcessInitInfoWithMatcher对象将监视具有匹配UniqueWindowHostId属性的WindowInfo对象,当此类对象到达时,它将使用其WindowHandle属性将Python窗口插入当前DockItem对象。
Python代码
这三个Python项目都非常相似,所以,这里我只描述其中的一个——DotPyMatPlog.py。
以下是该程序的文档代码:
imports ...
class ApplicationWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
# create QWidget, its layout and canvas for the figure
self._main = QtWidgets.QWidget()
self.setCentralWidget(self._main)
layout = QtWidgets.QVBoxLayout(self._main)
layout.setContentsMargins(0,0,0,0)
canvas = FigureCanvas()
layout.addWidget(canvas)
# generate data for the plot
np.random.seed(19680801)
data = {'a': np.arange(50),
'c': np.random.randint(0, 50, 50),
'd': np.random.randn(50)}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100
#end generate data for the plot
# create plot
plt = canvas.figure.subplots()
#paint the dots
plt.scatter('a', 'b', c='c', s='d', data=data)
#set the names of the axes of the plot
plt.set_xlabel('entry a')
plt.set_ylabel('entry b')
def main(argv):
sys.path.append(r'..\CommonPython\env\Lib\site-packages')
import Messages_pb2 as messages
# Check whether there is already a running QApplication (e.g., if running
# from an IDE).
qapp = QtWidgets.QApplication.instance()
if not qapp:
qapp = QtWidgets.QApplication(sys.argv)
#create and show the window
app = ApplicationWindow()
app.show()
app.activateWindow()
# get the handle of the window
winhandle = int(app.winId())
print(winhandle);
# argument means that the Python program is started from the C# code
if len(argv) > 0:
app.unique_window_host_id = argv[0]; #unique window host id
#create Relay Client
broadcastingClient = BroadcastingRelayClient("localhost", 5051)
# connect the relay client to the server
broadcastingClient.connect_if_needed()
# create the WindowInfo object containing the UniqueWindowHostId
# and the WindowHandle
winInfo = messages.WindowInfo(WindowHandle=winhandle,
UniqueWindowHostId=app.unique_window_host_id)
#publish the WindowInfo object to the Relay Server
broadcastingClient.broadcast_object(winInfo, "WindowInfoTopic", 1)
app.raise_()
qapp.exec()
if __name__ == "__main__":
main(sys.argv[1:])
本质上,我们生成数据,然后在QT窗口中将其显示为(散点)图。
如果程序有一个命令行参数,我们假设它是UniqueWindowHostId,连接到在“localhost:5051”处运行的服务器,并发布回由UniqueWindowHostId和WindowHandle组成的服务器WindowInfo,我们通过调用winhandle = int(app.winId())。
在Linux上运行示例(Ubuntu——fluxbox)
不幸的是,Linux - Gnome环境搞砸了我们植入窗口。这是我试图在Avalonia和我自己之间解决的问题。所以,在这一点上,我只能在fluxbox上运行植入的应用程序。
首先,您需要在Linux上安装dotnet 6.0,python3,pip3和python3-tk(用于PySide6)。以下是在Ubuntu上安装它们的命令:
sudo apt-get install -y dotnet-sdk-6.0
sudo apt install python3
sudo apt install python3-pip
sudo apt-get install python3-tk
并在需要时提供密码。
然后通过键入以下内容安装Linux软件包:
pip3 install numpy
pip3 install matplotlib
pip3 install grpcio
pip3 install NP.Grpc.PythonRelayInterfaces
pip3 install NP.Grpc.PythonMessages
pip3 install PySide6
pip3 install --upgrade protobuf
不知道为什么,但在我的例子中protobuf需要升级。
若要在Linux上运行该示例,需要在Windows上编译该示例,然后将解决方案的整个文件夹结构复制到Linux上。
cd到<RootDir>DockableAppsDemo/DockableAppImplantsDemo/bin/Debug/net6.0 并运行:
dotnet DockableAppImplantsDemo.dll
以下是您将看到的内容:
整个应用程序以与Windows非常相似的方式在Linux上显示,因为用于构建应用程序的所有组件(C#和Python)都是多平台的。
不幸的是,UniDock目前在Linux上移动可停靠窗口时存在一些问题,因此重新停靠单个绘图将不起作用。我计划尽快解决这些问题,因此窗口停靠应该在任何操作系统上都能正常工作。
https://www.codeproject.com/Articles/5355675/Embedding-Python-Applications-within-Gidon-Csharp