⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 jythonplugin.java

📁 Python Development Environment (Python IDE plugin for Eclipse). Features editor, code completion, re
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
	public static List<Throwable> execAll(HashMap<String, Object> locals, final String startingWith, IPythonInterpreter interpreter) {
		//exec files beneath jysrc in org.python.pydev.jython
		File jySrc = JythonPlugin.getJySrcDirFile();
		File additionalScriptingLocation = JyScriptingPreferencesPage.getAdditionalScriptingLocation();
        
		return execAll(locals, startingWith, interpreter, new File[]{jySrc, additionalScriptingLocation});
		
	}
    
    /**
     * Executes all the scripts beneath some folders
     * @param beneathFolders the folders we want to get the scripts from
     * @return the errors that occured while executing the scripts
     */
    public static List<Throwable> execAll(HashMap<String, Object> locals, final String startingWith, IPythonInterpreter interpreter, File[] beneathFolders) {
        List<Throwable> errors = new ArrayList<Throwable>();
        for (File file : beneathFolders) {
            if(file != null){
                if(!file.exists()){
                    String msg = "The folder:"+file+" does not exist and therefore cannot be used to " +
                                                "find scripts to run starting with:"+startingWith;
                    Log.log(IStatus.ERROR, msg, null);
                    errors.add(new RuntimeException(msg));
                }
                File[] files = getFilesBeneathFolder(startingWith, file);
                if(files != null){
                    for(File f : files){
                        Throwable throwable = exec(locals, interpreter, f, beneathFolders);
                        if(throwable != null){
                            errors.add(throwable);
                        }
                    }
                }
            }
        }
        return errors;
    }
	/**
	 * List all the 'target' scripts available beneath some folder.
	 */
	public static File[] getFilesBeneathFolder(final String startingWith, File jySrc) {
		File[] files = jySrc.listFiles(new FileFilter(){

			public boolean accept(File pathname) {
				String name = pathname.getName();
                if(name.startsWith(startingWith) && name.endsWith(".py")){
					return true;
				}
				return false;
			}
			
		});
		return files;
	}


	/**
	 * Holds a cache with the name of the created code to a tuple with the file timestamp and the Code Object
	 * that was generated with the contents of that timestamp.
	 */
	private static Map<File, Tuple<Long, Object>> codeCache = new HashMap<File,Tuple<Long, Object>>();
	
	/**
	 * @param pythonpathFolders folders that should be in the pythonpath when executing the script
	 * @see JythonPlugin#exec(HashMap, String, PythonInterpreter)
	 * Same as before but the file to execute is passed as a parameter
	 */
	public static synchronized Throwable exec(HashMap<String, Object> locals, IPythonInterpreter interpreter, File fileToExec, File[] pythonpathFolders) {
        if(locals == null){
            locals = new HashMap<String, Object>();
        }
		synchronized (codeCache) { //hold on there... one at a time... please?
			try {
			    String fileName = fileToExec.getName();
	            if(!fileName.endsWith(".py")){
	                throw new RuntimeException("The script to be executed must be a python file. Name:"+fileName);
	            }
	            String codeObjName = "code"+fileName.substring(0, fileName.indexOf('.'));
	            final String codeObjTimestampName = codeObjName+"Timestamp";
	            
				for (Map.Entry<String, Object> entry : locals.entrySet()) {
					interpreter.set(entry.getKey(), entry.getValue());
				}
				
				boolean regenerate = false;
				Tuple<Long, Object> timestamp = codeCache.get(fileToExec);
				final long lastModified = fileToExec.lastModified();
				if(timestamp == null || timestamp.o1 != lastModified){
					//the file timestamp changed, so, we have to regenerate it
					regenerate = true;
				}
				
				if(!regenerate){
					//if the 'code' object does not exist or if it's timestamp is outdated, we have to re-set it. 
					PyObject obj = interpreter.get(codeObjName);
					PyObject pyTime = interpreter.get(codeObjTimestampName);
					if (obj == null || pyTime == null || !pyTime.__tojava__(Long.class).equals(timestamp.o1)){
						if(DEBUG){
							System.out.println("Resetting object: "+codeObjName);
						}
						interpreter.set(codeObjName, timestamp.o2);
						interpreter.set(codeObjTimestampName, timestamp.o1);
					}
				}
				
				if(regenerate){
					if(DEBUG){
						System.out.println("Regenerating: "+codeObjName);
					}
					String path = REF.getFileAbsolutePath(fileToExec);
	                
	                StringBuffer strPythonPathFolders = new StringBuffer();
	                strPythonPathFolders.append("[");
	                for (File file : pythonpathFolders) {
                        if (file != null){
    	                    strPythonPathFolders.append("r'");
    	                    strPythonPathFolders.append(REF.getFileAbsolutePath(file));
    	                    strPythonPathFolders.append("',");
                        }
	                }
	                strPythonPathFolders.append("]");
                    
                    StringBuffer addToSysPath = new StringBuffer();
                    
                    //we will only add the paths to the pythonpath if it was still not set or if it changed (but it will never remove the ones added before).
                    addToSysPath.append("if not hasattr(sys, 'PYDEV_PYTHONPATH_SET') or sys.PYDEV_PYTHONPATH_SET != "); //we have to put that in sys because it is the same across different interpreters
                    addToSysPath.append(strPythonPathFolders);
                    addToSysPath.append(":\n");
                    
                    addToSysPath.append("    sys.PYDEV_PYTHONPATH_SET = ");
                    addToSysPath.append(strPythonPathFolders);
                    addToSysPath.append("\n");
                    
                    addToSysPath.append("    sys.path += ");
                    addToSysPath.append(strPythonPathFolders);
                    addToSysPath.append("\n");
                    
	                String toExec = StringUtils.format(LOAD_FILE_SCRIPT, path, path, addToSysPath.toString());
	                interpreter.exec(toExec);
					String exec = StringUtils.format("%s = compile(toExec, r'%s', 'exec')", codeObjName, path);
					interpreter.exec(exec);
					//set its timestamp
					interpreter.set(codeObjTimestampName, lastModified);
					
					Object codeObj = interpreter.get(codeObjName);
					codeCache.put(fileToExec, new Tuple<Long, Object>(lastModified, codeObj));
				}
				
				interpreter.exec(StringUtils.format("exec(%s)" , codeObjName));
			} catch (Throwable e) {
                if(!IN_TESTS && JythonPlugin.getDefault() == null){
                    //it is already disposed
                    return null;
                }
				//the user requested it to exit
				if(e instanceof ExitScriptException){
					return null;
				}
				//actually, this is more likely to happen when raising an exception in jython
				if(e instanceof PyException){
					PyException pE = (PyException) e;
					if (pE.type instanceof PyJavaClass){
						PyJavaClass t = (PyJavaClass) pE.type;
						if(t.__name__ != null && t.__name__.equals("org.python.pydev.jython.ExitScriptException")){
							return null;
						}
					}
				}
				
				if(JyScriptingPreferencesPage.getShowScriptingOutput()){
					Log.log(IStatus.ERROR, "Error while executing:"+fileToExec, e);
				}
                return e;
			}
		}
        return null;
	}


    
    // -------------- static things
    
    /**
     * This is the console we are writing to
     */
    private static MessageConsole fConsole;

    /**
     * @return the console to use
     */
    private static MessageConsole getConsole() {
        try {
            if (fConsole == null) {
                fConsole = new MessageConsole("", JythonPlugin.getBundleInfo().getImageCache().getDescriptor("icons/python.gif"));
                ConsolePlugin.getDefault().getConsoleManager().addConsoles(new IConsole[] { fConsole });
            }
            return fConsole;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static IPythonInterpreter newPythonInterpreter() {
        return newPythonInterpreter(true);
    }
    
    /**
     * Creates a new Python interpreter (with jython) and returns it.
     */
	public static IPythonInterpreter newPythonInterpreter(boolean redirect) {
		PythonInterpreterWrapper interpreter = new PythonInterpreterWrapper();
        if(redirect){
    		interpreter.setOut(new ScriptOutput(getBlack(), getConsole()));
    		interpreter.setErr(new ScriptOutput(getRed(), getConsole()));
        }
		interpreter.set("False", 0);
		interpreter.set("True", 1);
		return interpreter;
	}
	
	static Color red;
	static Color black;
    static Color green;
    
    
	public static Color getRed() {
		if(red == null){
			synchronized (Display.getDefault()) {
				Display.getDefault().syncExec(new Runnable(){
					
					public void run() {
						red = Display.getDefault().getSystemColor(SWT.COLOR_RED);
					}
				});
			}
		}
		return red;
	}
	
	public static Color getBlack() {
		if(black == null){
			synchronized (Display.getDefault()) {
				Display.getDefault().syncExec(new Runnable(){

					public void run() {
						black = Display.getDefault().getSystemColor(SWT.COLOR_BLACK);
					}
				});
			}
		}
		return black;
	}
	public static Color getGreen() {
	    if(green == null){
	        synchronized (Display.getDefault()) {
	            Display.getDefault().syncExec(new Runnable(){
	                
	                public void run() {
                        green = new Color(Display.getDefault(), 0, 200, 125);
	                }
	            });
	        }
	    }
	    return green;
	}
    
    public static IInteractiveConsole newInteractiveConsole() {
        return new InteractiveConsoleWrapper();
    }
	

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -