我想要实现的目标
在.NET Core 3.1的后期构建中运行Python 3.7脚本,这样它就可以在Linux和Windows上开箱即用。
我做出的假设
- 将在其上构建项目的机器上,我们将安装至少2个版本的Python,即2.7和3.6+
- 两个Python版本都在PATH中
- 我希望避免任何操作,如重命名二进制文件或编辑PATH等。这应该是开箱即用的,没有任何黑客攻击
其他问题
为了访问脚本,我使用MSBuild宏,如$(SolutionDir)
,因此路径脚本将依赖于操作系统,因为/
和
我尝试了什么
我的理解是:让Python 2.x和3.x并行安装,确保脚本将使用Python 3.x执行的最简单方法是在Windows上使用py -3
,在Linux上使用python3
。由于调用python
将在使用Python2.x执行脚本时生效。
我试图通过至少3种不同的方式强制MSBuild运行不同的构建后脚本:
(1(
<ItemDefinitionGroup>
<PostBuildEvent Condition="'$(OS)' == 'Unix' ">
<Message>Uisng post-build scripts for Unix/Linux
</Message>
<Command>python3 $(SolutionDir)BuildToolsPostBuild.py -s $(SolutionDir) -p $(ProjectPath) -c $(ConfigurationName) -t $(TargetDir) -n $(ProjectName)
</Command>
</PostBuildEvent>
<PostBuildEvent Condition="'$(OS)' == 'Windows_NT' ">
<Message>Using post-build scripts for Windows
</Message>
<Command>py -3 $(SolutionDir)BuildTools/PostBuild.py -s $(SolutionDir) -p $(ProjectPath) -c $(ConfigurationName) -t $(TargetDir) -n $(ProjectName)
</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
(2(
<Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="'$(OS)' == 'Windows_NT'">
<Exec Command="py -3 $(SolutionDir)BuildToolsPostBuild.py -s $(SolutionDir) -p $(ProjectPath) -c $(ConfigurationName) -t $(TargetDir) -n $(ProjectName) -o $(TargetPath) -f $(TargetFileName)" />
</Target>
<Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="'$(OS)' == 'Unix'">
<Exec Command="python3 $(SolutionDir)BuildTools/PostBuild.py -s $(SolutionDir) -p $(ProjectPath) -c $(ConfigurationName) -t $(TargetDir) -n $(ProjectName) -o $(TargetPath) -f $(TargetFileName)" />
</Target>
(3(
<PropertyGroup>
(...)
<IsWindows Condition="'$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::Windows)))' == 'true'">true</IsWindows>
<IsLinux Condition="'$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::Linux)))' == 'true'">true</IsLinux>
</PropertyGroup>
然后将这个性质用于(2(和(3(中的条件。
但如果这些有效,就没有了。我错过了什么?或者我做错了什么?也许还有其他方法可以达到同样的效果?
非常感谢您的帮助!:(
Microsoft关于在项目文件中声明目标:https://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-targets?view=vs-2019#在项目文件中声明目标
这意味着,由于两个后构建事件的名称相同,第二个后构建会隐藏第一个,这意味着当您在Linux机器上运行时,唯一可以运行的后构建是Linux脚本。
要使其工作,请将代码更改为以下内容:
<Target Name="PostBuildWindows" AfterTargets="PostBuildEvent" Condition="'$(OS)' == 'Windows_NT'">
<Target Name="PostBuildLinux" AfterTargets="PostBuildEvent" Condition="'$(OS)' == 'Unix'">
你可以将名称值更改为任何你喜欢的值,但要确保它解释了它是什么。