Utilities/__init__.py

changeset 3446
5a670e55adbb
parent 3438
29717a5e8b97
child 3451
e9ee3ea73db4
child 3484
645c12de6b0c
--- a/Utilities/__init__.py	Fri Mar 28 19:52:34 2014 +0100
+++ b/Utilities/__init__.py	Sat Mar 29 20:12:47 2014 +0100
@@ -1287,6 +1287,70 @@
     return sys.hexversion >> 16
     
 
+def determinePythonVersion(filename, source, editor=None):
+    """
+    Function to determine the python version of a given file.
+    
+    @param filename name of the file with extension (str)
+    @param source of the file (str)
+    @keyparam editor reference to the editor, if the file is opened
+        already (Editor object)
+    @return Python version if file is Python2 or Python3 (int)
+    """
+    pyAssignment = {"Python": 2, "Python2": 2, "Python3": 3}
+    
+    if not editor:
+        viewManager = e5App().getObject('ViewManager')
+        editor = viewManager.getOpenEditor(filename)
+    
+    # Maybe the user has changed the language
+    if editor and editor.getFileType() in pyAssignment:
+        return pyAssignment[editor.getFileType()]
+
+    pyVer = 0
+    flags = extractFlags(source)
+    ext = os.path.splitext(filename)[1]
+    py2Ext = Preferences.getPython("PythonExtensions")
+    py3Ext = Preferences.getPython("Python3Extensions")
+    project = e5App().getObject('Project')
+    basename = os.path.basename(filename)
+    
+    if "FileType" in flags:
+        pyVer = pyAssignment.get(flags["FileType"], 0)
+    elif project.isOpen() and project.isProjectFile(filename):
+        language = project.getEditorLexerAssoc(basename)
+        if not language:
+            language = Preferences.getEditorLexerAssoc(basename)
+        if language in ['Python2', 'Python3']:
+            pyVer = pyAssignment[language]
+    
+    if pyVer:
+        # Skip the next tests
+        pass
+    elif (Preferences.getProject("DeterminePyFromProject") and
+          project.isOpen() and
+          project.isProjectFile(filename)):
+                pyVer = pyAssignment.get(project.getProjectLanguage(), 0)
+    elif ext in py2Ext and ext not in py3Ext:
+        pyVer = 2
+    elif ext in py3Ext and ext not in py2Ext:
+        pyVer = 3
+    elif source.startswith("#!"):
+        line0 = source.splitlines()[0]
+        if "python3" in line0:
+            pyVer = 3
+        elif "python" in line0:
+            pyVer = 2
+    
+    if pyVer == 0 and ext in py2Ext + py3Ext:
+        pyVer = sys.version_info[0]
+    
+    if editor and pyVer:
+        editor.filetype = "Python{0}".format(pyVer)
+    
+    return pyVer
+
+
 def compile(file, codestring=""):
     """
     Function to compile one Python source file to Python bytecode.

eric ide

mercurial