_env = os.environ _PYTHONPATH = 'PYTHONPATH' def get_python(py3=False): env = dict(_env) env.pop(_PYTHONPATH, None) pyexe = 'python2' if not py3 else 'python3' import subprocess as sub p = sub.Popen(pyexe, env=env, stdin=sub.PIPE, stdout=sub.PIPE, stderr=sub.PIPE, universal_newlines=True) p.stdin.write('import sys\n') p.stdin.write('print("EXEC|" + sys.executable)\n') p.stdin.write('print("PATH|" + "|".join(sys.path))\n') p.stdin.write('import os\n') p.stdin.write('if sys.platform == "win32":\n') p.stdin.write(' key = "PATH"\n') p.stdin.write('elif sys.platform == "darwin":\n') p.stdin.write(' key = "DYLD_LIBRARY_PATH"\n') p.stdin.write('else:\n') p.stdin.write(' key = "LD_LIBRARY_PATH"\n') p.stdin.write('lp = os.environ[key].split(os.pathsep)\n') p.stdin.write('print("LDPATH|" + "|".join(lp))\n') p.stdin.close() exe, path, ldpath = parse_for_env(p.stdout, sep='|') if exe is None: raise RuntimeError('Problem with running external process: ' + p.stderr.read()) return exe, path, ldpath print get_python()