33import { IPythonProcess , IPythonThread , IPythonModule , IPythonEvaluationResult } from "./Contracts" ;
44import * as path from "path" ;
55import * as fs from 'fs' ;
6+ import * as child_process from 'child_process' ;
7+
8+ export const IS_WINDOWS = / ^ w i n / . test ( process . platform ) ;
9+ export const PATH_VARIABLE_NAME = IS_WINDOWS ? 'Path' : 'PATH' ;
610
711const PathValidity : Map < string , boolean > = new Map < string , boolean > ( ) ;
812export function validatePath ( filePath : string ) : Promise < string > {
@@ -66,3 +70,45 @@ export function FixupEscapedUnicodeChars(value: string): string {
6670 return value ;
6771}
6872
73+ export function getPythonExecutable ( pythonPath : string ) : string {
74+ // If only 'python'
75+ if ( pythonPath === 'python' ||
76+ pythonPath . indexOf ( path . sep ) === - 1 ||
77+ path . basename ( pythonPath ) === path . dirname ( pythonPath ) ) {
78+ return pythonPath ;
79+ }
80+
81+ if ( isValidPythonPath ( pythonPath ) ) {
82+ return pythonPath ;
83+ }
84+
85+ // Suffix with 'python' for linux and 'osx', and 'python.exe' for 'windows'
86+ if ( IS_WINDOWS ) {
87+ if ( isValidPythonPath ( path . join ( pythonPath , 'python.exe' ) ) ) {
88+ return path . join ( pythonPath , 'python.exe' ) ;
89+ }
90+ if ( isValidPythonPath ( path . join ( pythonPath , 'scripts' , 'python.exe' ) ) ) {
91+ return path . join ( pythonPath , 'scripts' , 'python.exe' ) ;
92+ }
93+ }
94+ else {
95+ if ( isValidPythonPath ( path . join ( pythonPath , 'python' ) ) ) {
96+ return path . join ( pythonPath , 'python' ) ;
97+ }
98+ if ( isValidPythonPath ( path . join ( pythonPath , 'bin' , 'python' ) ) ) {
99+ return path . join ( pythonPath , 'bin' , 'python' ) ;
100+ }
101+ }
102+
103+ return pythonPath ;
104+ }
105+
106+ function isValidPythonPath ( pythonPath ) : boolean {
107+ try {
108+ let output = child_process . execFileSync ( pythonPath , [ '-c' , 'print(1234)' ] , { encoding : 'utf8' } ) ;
109+ return output . startsWith ( '1234' ) ;
110+ }
111+ catch ( ex ) {
112+ return false ;
113+ }
114+ }
0 commit comments