-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFindPythonTask.targets
74 lines (65 loc) · 2.09 KB
/
FindPythonTask.targets
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- From: https://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-roslyncodetaskfactory -->
<UsingTask TaskName="FindPythonTask" TaskFactory="RoslynCodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll">
<Task>
<Code Type="Class" Language="cs">
<![CDATA[
#nullable enable
using System;
using System.Diagnostics;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Task = Microsoft.Build.Utilities.Task;
public class FindPythonTask : Task
{
[Output]
public string PythonPath { get; set; } = "";
private static string? CachedPythonPath;
public override bool Execute()
{
if (CachedPythonPath != null) {
PythonPath = CachedPythonPath;
return true;
}
string[] pythons = {
"python3",
"python"
};
foreach (string python in pythons) {
if (IsPythonValid(python)) {
PythonPath = python;
CachedPythonPath = python;
return true;
}
}
Log.LogError($"Couldn't not find python on the PATH. Tried: {pythons}");
return false;
}
private bool IsPythonValid(string python)
{
bool isPythonValid = false;
Process process = new Process();
process.StartInfo = new ProcessStartInfo {
FileName = python,
CreateNoWindow = true,
Arguments = "--version",
RedirectStandardOutput = true
};
try {
process.Start();
try {
process.WaitForExit(1000 * 10);
string outputLine = process.StandardOutput.ReadLine() ?? "";
isPythonValid = outputLine.ToLowerInvariant().StartsWith("python 3");
} finally {
process.Kill();
}
} catch { }
return isPythonValid;
}
}
]]>
</Code>
</Task>
</UsingTask>
</Project>