.NET Core 3.1以独立于平台的方式运行Python 3.7编译后脚本

2024-09-28 05:44:35 发布

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

我想实现的

在.NET Core 3.1的后期构建中运行Python3.7脚本,这样它就可以在Linux和Windows上开箱即用

我做出的假设

  • 我们将至少安装2个版本的Python,即2.7和3.6+
  • 两个Python版本都在PATH中
  • 我想避免任何操作,如重命名二进制文件或编辑路径等。这应该是开箱即用的,没有任何黑客

其他问题

为了访问脚本,我使用了MSBuild宏,例如$(SolutionDir),因此路径脚本将依赖于操作系统,因为/\

我尝试的

我的理解是:并行安装Python2.x和3.x确保使用Python3.x执行脚本最简单的方法是在Windows上使用py -3,在Linux上使用python3。As调用python将在使用Python2.x执行脚本时生效

我尝试强制MSBuild以至少3种不同的方式运行不同的生成后脚本:

(一)

<ItemDefinitionGroup>
  <PostBuildEvent Condition="'$(OS)' == 'Unix' ">
    <Message>Uisng post-build scripts for Unix/Linux
      </Message>
    <Command>python3 $(SolutionDir)BuildTools\PostBuild.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>

(二)

<Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="'$(OS)' == 'Windows_NT'">
  <Exec Command="py -3 $(SolutionDir)BuildTools\PostBuild.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>

(三)

<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)中的条件使用此属性

但如果这些措施奏效的话,就没有了。我错过了什么?或者我做错了什么?也许还有其他方法可以达到同样的效果

非常感谢您的帮助!:)


Tags: py脚本messageoslinuxwindowsconditioncommand
1条回答
网友
1楼 · 发布于 2024-09-28 05:44:35

Microsoft关于在项目文件中声明目标:https://docs.microsoft.com/en-us/visualstudio/msbuild/msbuild-targets?view=vs-2019#declare-targets-in-the-project-file

这意味着,由于两个后期生成事件的名称相同,第二个后期生成将隐藏第一个,这意味着在Linux机器上运行时,可以运行的唯一后期生成是Linux脚本

要使其正常工作,请将代码更改为以下内容:

<Target Name="PostBuildWindows" AfterTargets="PostBuildEvent" Condition="'$(OS)' == 'Windows_NT'">

<Target Name="PostBuildLinux" AfterTargets="PostBuildEvent" Condition="'$(OS)' == 'Unix'">

您可以将名称值更改为任何您喜欢的值,但请确保它解释了它是什么

相关问题 更多 >

    热门问题