@Override
  public void consume(@Nullable AbstractProjectSettingsStep settingsStep) {
    if (myRunnable != null) {
      myRunnable.run();
    }
    if (settingsStep == null) return;

    Sdk sdk = settingsStep.getSdk();
    final Project project = ProjectManager.getInstance().getDefaultProject();
    final ProjectSdksModel model = PyConfigurableInterpreterList.getInstance(project).getModel();
    if (sdk instanceof PyDetectedSdk) {
      final String name = sdk.getName();
      VirtualFile sdkHome =
          ApplicationManager.getApplication()
              .runWriteAction(
                  new Computable<VirtualFile>() {
                    @Override
                    public VirtualFile compute() {
                      return LocalFileSystem.getInstance().refreshAndFindFileByPath(name);
                    }
                  });
      PySdkService.getInstance().solidifySdk(sdk);
      sdk =
          SdkConfigurationUtil.setupSdk(
              ProjectJdkTable.getInstance().getAllJdks(),
              sdkHome,
              PythonSdkType.getInstance(),
              true,
              null,
              null);
      model.addSdk(sdk);
      settingsStep.setSdk(sdk);
      try {
        model.apply();
      } catch (ConfigurationException exception) {
        LOG.error("Error adding detected python interpreter " + exception.getMessage());
      }
    }
    Project newProject = generateProject(project, settingsStep);
    if (newProject != null) {
      SdkConfigurationUtil.setDirectoryProjectSdk(newProject, sdk);
      final List<Sdk> sdks = PythonSdkType.getAllSdks();
      for (Sdk s : sdks) {
        final SdkAdditionalData additionalData = s.getSdkAdditionalData();
        if (additionalData instanceof PythonSdkAdditionalData) {
          ((PythonSdkAdditionalData) additionalData).reassociateWithCreatedProject(newProject);
        }
      }
    }
  }
  protected GeneralCommandLine createCommandLine(Module module, List<String> params)
      throws ExecutionException {
    GeneralCommandLine cmd = new GeneralCommandLine();

    Sdk sdk = PythonSdkType.findPythonSdk(module);
    if (sdk == null) {
      throw new ExecutionException("No sdk specified");
    }

    ReSTService service = ReSTService.getInstance(module);
    cmd.setWorkDirectory(
        service.getWorkdir().isEmpty()
            ? module.getProject().getBaseDir().getPath()
            : service.getWorkdir());
    PythonCommandLineState.createStandardGroupsIn(cmd);
    ParamsGroup script_params =
        cmd.getParametersList().getParamsGroup(PythonCommandLineState.GROUP_SCRIPT);
    assert script_params != null;

    String commandPath = getCommandPath(sdk);
    if (commandPath == null) {
      throw new ExecutionException("Cannot find sphinx-quickstart.");
    }
    cmd.setExePath(commandPath);

    if (params != null) {
      for (String p : params) {
        script_params.addParameter(p);
      }
    }

    cmd.setPassParentEnvironment(true);
    setPythonIOEncoding(cmd.getEnvironment(), "utf-8");
    setPythonUnbuffered(cmd.getEnvironment());

    List<String> pathList = Lists.newArrayList(PythonCommandLineState.getAddedPaths(sdk));
    pathList.addAll(PythonCommandLineState.collectPythonPath(module));

    PythonCommandLineState.initPythonPath(cmd, true, pathList, sdk.getHomePath());

    PythonSdkType.patchCommandLineForVirtualenv(cmd, sdk.getHomePath(), true);
    BuildoutFacet facet = BuildoutFacet.getInstance(module);
    if (facet != null) {
      facet.patchCommandLineForBuildout(cmd);
    }

    return cmd;
  }
  /**
   * Patches the command line parameters applying patchers from first to last, and then runs it.
   *
   * @param patchers any number of patchers; any patcher may be null, and the whole argument may be
   *     null.
   * @return handler of the started process
   * @throws ExecutionException
   */
  protected ProcessHandler startProcess(CommandLinePatcher... patchers) throws ExecutionException {
    GeneralCommandLine commandLine = generateCommandLine(patchers);

    // Extend command line
    PythonRunConfigurationExtensionsManager.getInstance()
        .patchCommandLine(
            myConfig, getRunnerSettings(), commandLine, getEnvironment().getRunner().getRunnerId());
    Sdk sdk = PythonSdkType.findSdkByPath(myConfig.getInterpreterPath());
    final ProcessHandler processHandler;
    if (PySdkUtil.isRemote(sdk)) {
      PyRemotePathMapper pathMapper = createRemotePathMapper();
      processHandler =
          createRemoteProcessStarter()
              .startRemoteProcess(sdk, commandLine, myConfig.getProject(), pathMapper);
    } else {
      EncodingEnvironmentUtil.setLocaleEnvironmentIfMac(commandLine);
      processHandler = doCreateProcess(commandLine);
      ProcessTerminatedListener.attach(processHandler);
    }

    // attach extensions
    PythonRunConfigurationExtensionsManager.getInstance()
        .attachExtensionsToProcess(myConfig, processHandler, getRunnerSettings());

    return processHandler;
  }
  private void addCreatedSdk(@Nullable final Sdk sdk, boolean newVirtualEnv) {
    if (sdk != null) {
      final PySdkService sdkService = PySdkService.getInstance();
      sdkService.restoreSdk(sdk);

      boolean isVirtualEnv = PythonSdkType.isVirtualEnv(sdk);
      if (isVirtualEnv && !newVirtualEnv) {
        AddVEnvOptionsDialog dialog = new AddVEnvOptionsDialog(myMainPanel);
        dialog.show();
        if (dialog.getExitCode() != DialogWrapper.OK_EXIT_CODE) {
          return;
        }
        SdkModificator modificator = myModificators.get(sdk);
        setSdkAssociated(modificator, !dialog.makeAvailableToAll());
        myModifiedModificators.add(modificator);
      }
      final Sdk oldSdk = myProjectSdksModel.findSdk(sdk);
      if (oldSdk == null) {
        myProjectSdksModel.addSdk(sdk);
      }
      refreshSdkList();
      mySdkList.setSelectedValue(myProjectSdksModel.findSdk(sdk.getName()), true);
      mySdkListChanged = true;
    }
  }
 private TextConsoleBuilder createConsoleBuilder(Project project) {
   if (isDebug()) {
     return new PyDebugConsoleBuilder(
         project, PythonSdkType.findSdkByPath(myConfig.getInterpreterPath()));
   } else {
     return TextConsoleBuilderFactory.getInstance().createBuilder(project);
   }
 }
 private static void buildPythonPath(
     Project project, GeneralCommandLine commandLine, PythonRunParams config) {
   Sdk pythonSdk = PythonSdkType.findSdkByPath(config.getSdkHome());
   if (pythonSdk != null) {
     List<String> pathList = Lists.newArrayList(getAddedPaths(pythonSdk));
     pathList.addAll(collectPythonPath(project, config));
     initPythonPath(commandLine, config.isPassParentEnvs(), pathList, config.getSdkHome());
   }
 }
 @Override
 public void run(@NotNull Sdk sdk) {
   final PythonRemoteInterpreterManager manager = PythonRemoteInterpreterManager.getInstance();
   if (manager != null) {
     try {
       manager.runVagrant(myVagrantFolder, myMachineName);
       PythonSdkType.getInstance().setupSdkPaths(sdk);
     } catch (ExecutionException e) {
       throw new RuntimeException(e);
     }
   }
 }
  @Nullable
  public static String getInterpreterPath(Project project, PythonRunParams config) {
    String sdkHome = config.getSdkHome();
    if (config.isUseModuleSdk() || StringUtil.isEmpty(sdkHome)) {
      Module module = getModule(project, config);

      Sdk sdk = PythonSdkType.findPythonSdk(module);
      if (sdk == null) return null;
      sdkHome = sdk.getHomePath();
    }

    return sdkHome;
  }
 private boolean generateSkeletonsForList(
     @NotNull final PySkeletonRefresher refresher,
     ProgressIndicator indicator,
     @Nullable final String currentBinaryFilesPath)
     throws InvalidSdkException {
   final PySkeletonGenerator generator =
       new PySkeletonGenerator(refresher.getSkeletonsPath(), mySdk, currentBinaryFilesPath);
   indicator.setIndeterminate(false);
   final String homePath = mySdk.getHomePath();
   if (homePath == null) return false;
   final ProcessOutput runResult =
       PySdkUtil.getProcessOutput(
           new File(homePath).getParent(),
           new String[] {
             homePath, PythonHelpersLocator.getHelperPath("extra_syspath.py"), myQualifiedName
           },
           PythonSdkType.getVirtualEnvExtraEnv(homePath),
           5000);
   if (runResult.getExitCode() == 0 && !runResult.isTimeout()) {
     final String extraPath = runResult.getStdout();
     final PySkeletonGenerator.ListBinariesResult binaries =
         generator.listBinaries(mySdk, extraPath);
     final List<String> names = Lists.newArrayList(binaries.modules.keySet());
     Collections.sort(names);
     final int size = names.size();
     for (int i = 0; i != size; ++i) {
       final String name = names.get(i);
       indicator.setFraction((double) i / size);
       if (needBinaryList(name)) {
         indicator.setText2(name);
         final PySkeletonRefresher.PyBinaryItem item = binaries.modules.get(name);
         final String modulePath = item != null ? item.getPath() : "";
         //noinspection unchecked
         refresher.generateSkeleton(
             name, modulePath, new ArrayList<String>(), Consumer.EMPTY_CONSUMER);
       }
     }
   }
   return true;
 }
 public static boolean isIpythonNewFormat(@NotNull final VirtualFile virtualFile) {
   final Project project = ProjectUtil.guessProjectForFile(virtualFile);
   if (project != null) {
     final Module module =
         ProjectRootManager.getInstance(project).getFileIndex().getModuleForFile(virtualFile);
     if (module != null) {
       final Sdk sdk = PythonSdkType.findPythonSdk(module);
       if (sdk != null) {
         // It should be called first before IpnbConnectionManager#startIpythonServer()
         final List<PyPackage> packages = PyPackageUtil.refreshAndGetPackagesModally(sdk);
         final PyPackage ipython =
             packages != null ? PyPackageUtil.findPackage(packages, "ipython") : null;
         final PyPackage jupyter =
             packages != null ? PyPackageUtil.findPackage(packages, "jupyter") : null;
         if (jupyter == null
             && ipython != null
             && VersionComparatorUtil.compare(ipython.getVersion(), "3.0") <= 0) {
           return false;
         }
       }
     }
   }
   return true;
 }
 @Override
 public Sdk findSdk(@NotNull final Project project) {
   return PythonSdkType.findPythonSdk(ModuleManager.getInstance(project).getModules()[0]);
 }
 @Nullable
 private static Sdk getPythonSdk(@NotNull final PsiElement element) {
   final Module module = ModuleUtilCore.findModuleForPsiElement(element);
   return (module == null) ? null : PythonSdkType.findPythonSdk(module);
 }
 @Override
 public String getInstallToUserText() {
   String userSiteText = "Install to user's site packages directory";
   if (!PythonSdkType.isRemote(mySdk)) userSiteText += " (" + PySdkUtil.getUserSite() + ")";
   return userSiteText;
 }
 @Override
 public boolean canInstallToUser() {
   return !PythonSdkType.isVirtualEnv(mySdk);
 }