Search in sources :

Example 1 with SimplePythonRunner

use of org.python.pydev.ast.runners.SimplePythonRunner in project Pydev by fabioz.

the class Pep8Runner method runWithPep8BaseScript.

/**
 * @param fileContents the contents to be passed in the stdin.
 * @param parameters the parameters to pass. Note that a '-' is always added to the parameters to signal we'll pass the file as the input in stdin.
 * @param script i.e.: pycodestyle.py, autopep8.py
 * @return null if there was some error, otherwise returns the process stdout output.
 */
public static String runWithPep8BaseScript(IDocument doc, String parameters, String script) {
    File autopep8File;
    try {
        autopep8File = CorePlugin.getScriptWithinPySrc(new Path("third_party").append("pep8").append(script).toString());
    } catch (CoreException e) {
        Log.log("Unable to get " + script + " location.");
        return null;
    }
    if (!autopep8File.exists()) {
        Log.log("Specified location for " + script + " does not exist (" + autopep8File + ").");
        return null;
    }
    SimplePythonRunner simplePythonRunner = new SimplePythonRunner();
    IInterpreterManager pythonInterpreterManager = InterpreterManagersAPI.getPythonInterpreterManager();
    IInterpreterInfo defaultInterpreterInfo;
    try {
        defaultInterpreterInfo = pythonInterpreterManager.getDefaultInterpreterInfo(false);
    } catch (MisconfigurationException e) {
        Log.log("No default Python interpreter configured to run " + script);
        return null;
    }
    String[] parseArguments = ProcessUtils.parseArguments(parameters);
    List<String> lst = new ArrayList<>(Arrays.asList(parseArguments));
    lst.add("-");
    String[] cmdarray = SimplePythonRunner.preparePythonCallParameters(defaultInterpreterInfo.getExecutableOrJar(), autopep8File.toString(), lst.toArray(new String[0]));
    // Try to find the file's encoding, but if none is given or the specified encoding is
    // unsupported, then just default to utf-8
    String pythonFileEncoding = null;
    try {
        pythonFileEncoding = FileUtils.getPythonFileEncoding(doc, null);
        if (pythonFileEncoding == null) {
            pythonFileEncoding = "utf-8";
        }
    } catch (UnsupportedEncodingException e) {
        pythonFileEncoding = "utf-8";
    }
    final String encodingUsed = pythonFileEncoding;
    SystemPythonNature nature = new SystemPythonNature(pythonInterpreterManager, defaultInterpreterInfo);
    ICallback<String[], String[]> updateEnv = new ICallback<String[], String[]>() {

        @Override
        public String[] call(String[] arg) {
            if (arg == null) {
                arg = new String[] { "PYTHONIOENCODING=" + encodingUsed };
            } else {
                arg = ProcessUtils.addOrReplaceEnvVar(arg, "PYTHONIOENCODING", encodingUsed);
            }
            return arg;
        }
    };
    Tuple<Process, String> r = simplePythonRunner.run(cmdarray, autopep8File.getParentFile(), nature, new NullProgressMonitor(), updateEnv);
    try {
        r.o1.getOutputStream().write(doc.get().getBytes(pythonFileEncoding));
        r.o1.getOutputStream().close();
    } catch (IOException e) {
        Log.log("Error writing contents to " + script);
        return null;
    }
    Tuple<String, String> processOutput = SimplePythonRunner.getProcessOutput(r.o1, r.o2, new NullProgressMonitor(), pythonFileEncoding);
    if (processOutput.o2.length() > 0) {
        Log.log(processOutput.o2);
    }
    if (processOutput.o1.length() > 0) {
        return processOutput.o1;
    }
    return null;
}
Also used : Path(org.eclipse.core.runtime.Path) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) MisconfigurationException(org.python.pydev.core.MisconfigurationException) ArrayList(java.util.ArrayList) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SystemPythonNature(org.python.pydev.plugin.nature.SystemPythonNature) IOException(java.io.IOException) IInterpreterManager(org.python.pydev.core.IInterpreterManager) CoreException(org.eclipse.core.runtime.CoreException) ICallback(org.python.pydev.shared_core.callbacks.ICallback) IInterpreterInfo(org.python.pydev.core.IInterpreterInfo) SimplePythonRunner(org.python.pydev.ast.runners.SimplePythonRunner) File(java.io.File)

Example 2 with SimplePythonRunner

use of org.python.pydev.ast.runners.SimplePythonRunner in project Pydev by fabioz.

the class PipPackageManager method list.

/**
 * To be called from any thread
 */
@Override
public List<String[]> list() {
    List<String[]> listed = new ArrayList<String[]>();
    File pipExecutable;
    Tuple<String, String> output;
    try {
        pipExecutable = interpreterInfo.searchExecutableForInterpreter("pip", false);
        // use system encoding
        String encoding = null;
        output = new SimpleRunner().runAndGetOutput(new String[] { pipExecutable.toString(), "list", "--format=columns" }, null, null, null, encoding);
    } catch (UnableToFindExecutableException e) {
        IPythonNature nature = new SystemPythonNature(interpreterInfo.getModulesManager().getInterpreterManager(), interpreterInfo);
        String[] parameters = SimplePythonRunner.preparePythonCallParameters(interpreterInfo.getExecutableOrJar(), "-m", new String[] { getPipModuleName(interpreterInfo), "list", "--format=columns" });
        output = new SimplePythonRunner().runAndGetOutput(parameters, null, nature, null, "utf-8");
    }
    List<String> splitInLines = StringUtils.splitInLines(output.o1, false);
    for (String line : splitInLines) {
        line = line.trim();
        List<String> split = StringUtils.split(line, ' ');
        if (split.size() == 2) {
            String p0 = split.get(0).trim();
            String p1 = split.get(1).trim();
            if (p0.toLowerCase().equals("package") && p1.toLowerCase().equals("version")) {
                continue;
            }
            if (p0.toLowerCase().startsWith("--") && p1.toLowerCase().startsWith("--")) {
                continue;
            }
            listed.add(new String[] { p0.trim(), p1.trim(), "<pip>" });
        }
    }
    if (output.o2.toLowerCase().contains("no module named pip")) {
        listed.add(new String[] { "pip not installed (or not found) in interpreter", "", "" });
    } else {
        for (String s : StringUtils.iterLines(output.o2)) {
            listed.add(new String[] { s, "", "" });
        }
    }
    return listed;
}
Also used : SimpleRunner(org.python.pydev.ast.runners.SimpleRunner) UnableToFindExecutableException(org.python.pydev.core.IInterpreterInfo.UnableToFindExecutableException) ArrayList(java.util.ArrayList) IPythonNature(org.python.pydev.core.IPythonNature) SystemPythonNature(org.python.pydev.plugin.nature.SystemPythonNature) SimplePythonRunner(org.python.pydev.ast.runners.SimplePythonRunner) File(java.io.File)

Example 3 with SimplePythonRunner

use of org.python.pydev.ast.runners.SimplePythonRunner in project Pydev by fabioz.

the class PythonTest method exec.

@Override
protected Throwable exec(File f) {
    System.out.println(StringUtils.format("Running: %s", f));
    Tuple<String, String> output = new SimplePythonRunner().runAndGetOutput(new String[] { TestDependent.PYTHON2_EXE, "-u", FileUtils.getFileAbsolutePath(f) }, f.getParentFile(), null, null, "utf-8");
    System.out.println(StringUtils.format("stdout:%s\nstderr:%s", output.o1, output.o2));
    if (output.o2.toLowerCase().indexOf("failed") != -1 || output.o2.toLowerCase().indexOf("traceback") != -1) {
        throw new AssertionError(output.toString());
    }
    return null;
}
Also used : SimplePythonRunner(org.python.pydev.ast.runners.SimplePythonRunner)

Example 4 with SimplePythonRunner

use of org.python.pydev.ast.runners.SimplePythonRunner in project Pydev by fabioz.

the class AttachToProcess method doIt.

protected void doIt() throws Exception {
    IProcessList processList = PlatformUtils.getProcessList();
    IProcessInfo[] processList2 = processList.getProcessList();
    TreeNode<Object> root = new TreeNode<Object>(null, null);
    for (IProcessInfo iProcessInfo : processList2) {
        new TreeNode<>(root, iProcessInfo);
    }
    TreeNode<Object> element = new Select1Dialog() {

        @Override
        protected String getInitialFilter() {
            return "*python*";
        }

        @Override
        protected ILabelProvider getLabelProvider() {
            return new TreeNodeLabelProvider() {

                @Override
                public Image getImage(Object element) {
                    return ImageCache.asImage(SharedUiPlugin.getImageCache().get(UIConstants.PUBLIC_ATTR_ICON));
                }

                @SuppressWarnings("unchecked")
                @Override
                public String getText(Object element) {
                    if (element == null) {
                        return "null";
                    }
                    TreeNode<Object> node = (TreeNode<Object>) element;
                    Object data = node.data;
                    if (data instanceof IProcessInfo) {
                        IProcessInfo iProcessInfo = (IProcessInfo) data;
                        return iProcessInfo.getPid() + " - " + iProcessInfo.getName();
                    }
                    return "Unexpected: " + data;
                }
            };
        }
    }.selectElement(root);
    if (element != null) {
        IProcessInfo p = (IProcessInfo) element.data;
        int pid = p.getPid();
        if (!PydevRemoteDebuggerServer.isRunning()) {
            // I.e.: the remote debugger server must be on so that we can attach to it.
            PydevRemoteDebuggerServer.startServer();
        }
        // Select interpreter
        IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
        IInterpreterManager interpreterManager = InterpreterManagersAPI.getPythonInterpreterManager();
        if (interpreterManager == null) {
            MessageDialog.openError(workbenchWindow.getShell(), "No interpreter manager.", "No interpreter manager was available for attaching to a process.");
        }
        IInterpreterInfo[] interpreters = interpreterManager.getInterpreterInfos();
        if (interpreters == null || interpreters.length == 0) {
            MessageDialog.openError(workbenchWindow.getShell(), "No interpreters for creating console", "An interpreter that matches the architecture of the target process must be configured in the interpreter preferences.");
            return;
        }
        SelectionDialog listDialog = AbstractInterpreterPreferencesPage.createChooseIntepreterInfoDialog(workbenchWindow, interpreters, "Select interpreter which matches the architecture of the target process (i.e.: 32/64 bits).", false);
        int open = listDialog.open();
        if (open != ListDialog.OK || listDialog.getResult().length != 1) {
            return;
        }
        Object[] result = listDialog.getResult();
        IInterpreterInfo interpreter;
        if (result == null || result.length == 0) {
            interpreter = interpreters[0];
        } else {
            interpreter = ((IInterpreterInfo) result[0]);
        }
        SimplePythonRunner runner = new SimplePythonRunner();
        IPath relative = new Path("pysrc").append("pydevd_attach_to_process").append("attach_pydevd.py");
        String script = CorePlugin.getBundleInfo().getRelativePath(relative).getAbsolutePath();
        String[] args = new String[] { "--port", "" + DebugPluginPrefsInitializer.getRemoteDebuggerPort(), "--pid", "" + pid, "--protocol", "http" };
        IPythonNature nature = new SystemPythonNature(interpreterManager, interpreter);
        String[] s = SimplePythonRunner.preparePythonCallParameters(interpreter.getExecutableOrJar(), script, args);
        Tuple<Process, String> run = runner.run(s, (File) null, nature, new NullProgressMonitor());
        if (run.o1 != null) {
            ShowProcessOutputDialog dialog = new ShowProcessOutputDialog(UIUtils.getActiveShell(), run.o1);
            dialog.open();
        }
    }
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IProcessList(org.python.pydev.shared_core.utils.IProcessList) IPythonNature(org.python.pydev.core.IPythonNature) Image(org.eclipse.swt.graphics.Image) SelectionDialog(org.eclipse.ui.dialogs.SelectionDialog) TreeNode(org.python.pydev.shared_core.structure.TreeNode) TreeNodeLabelProvider(org.python.pydev.ui.dialogs.TreeNodeLabelProvider) IPath(org.eclipse.core.runtime.IPath) Path(org.eclipse.core.runtime.Path) IWorkbenchWindow(org.eclipse.ui.IWorkbenchWindow) IPath(org.eclipse.core.runtime.IPath) Select1Dialog(org.python.pydev.ui.dialogs.Select1Dialog) SystemPythonNature(org.python.pydev.plugin.nature.SystemPythonNature) IProcessInfo(org.python.pydev.shared_core.utils.IProcessInfo) ILabelProvider(org.eclipse.jface.viewers.ILabelProvider) IInterpreterManager(org.python.pydev.core.IInterpreterManager) IInterpreterInfo(org.python.pydev.core.IInterpreterInfo) SimplePythonRunner(org.python.pydev.ast.runners.SimplePythonRunner)

Example 5 with SimplePythonRunner

use of org.python.pydev.ast.runners.SimplePythonRunner in project Pydev by fabioz.

the class PythonInterpreterManager method doCreateInterpreterInfo.

/**
 * @param executable the python interpreter from where we should create the info
 * @param monitor a monitor to see the progress
 *
 * @return the created interpreter info
 * @throws CoreException
 */
public static Tuple<InterpreterInfo, String> doCreateInterpreterInfo(String executable, IProgressMonitor monitor, boolean askUser) throws CoreException {
    boolean isJythonExecutable = InterpreterInfo.isJythonExecutable(executable);
    if (isJythonExecutable) {
        throw new RuntimeException("A jar cannot be used in order to get the info for the python interpreter.");
    }
    File script = getInterpreterInfoPy();
    Tuple<String, String> outTup = new SimplePythonRunner().runAndGetOutputWithInterpreter(executable, FileUtils.getFileAbsolutePath(script), null, null, null, monitor, "utf-8");
    InterpreterInfo info = createInfoFromOutput(monitor, outTup, askUser, executable, true);
    if (info == null) {
        // cancelled
        return null;
    }
    info.restoreCompiledLibs(monitor);
    return new Tuple<InterpreterInfo, String>(info, outTup.o1);
}
Also used : SimplePythonRunner(org.python.pydev.ast.runners.SimplePythonRunner) File(java.io.File) Tuple(org.python.pydev.shared_core.structure.Tuple)

Aggregations

SimplePythonRunner (org.python.pydev.ast.runners.SimplePythonRunner)7 File (java.io.File)5 ArrayList (java.util.ArrayList)3 Path (org.eclipse.core.runtime.Path)3 SystemPythonNature (org.python.pydev.plugin.nature.SystemPythonNature)3 CoreException (org.eclipse.core.runtime.CoreException)2 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)2 SimpleRunner (org.python.pydev.ast.runners.SimpleRunner)2 IInterpreterInfo (org.python.pydev.core.IInterpreterInfo)2 IInterpreterManager (org.python.pydev.core.IInterpreterManager)2 IPythonNature (org.python.pydev.core.IPythonNature)2 MisconfigurationException (org.python.pydev.core.MisconfigurationException)2 ExternalAnalizerProcessWatchDoc (com.python.pydev.analysis.external.ExternalAnalizerProcessWatchDoc)1 IOException (java.io.IOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 StringTokenizer (java.util.StringTokenizer)1 IFile (org.eclipse.core.resources.IFile)1 IProject (org.eclipse.core.resources.IProject)1 IPath (org.eclipse.core.runtime.IPath)1 ILabelProvider (org.eclipse.jface.viewers.ILabelProvider)1