Fixes #49191 make "__file__" available to scripts

This commit is contained in:
Yoann Quenach de Quivillic 2023-03-03 15:57:24 +01:00
parent 08c7d66e30
commit a1a43e5362
2 changed files with 21 additions and 4 deletions

View File

@ -324,8 +324,8 @@ class Editor(QgsCodeEditorPython):
filename = self.createTempFile() filename = self.createTempFile()
deleteTempFile = True deleteTempFile = True
self.pythonconsole.shell.runCommand("exec(Path('{0}').read_text())" self.pythonconsole.shell.runFile(filename)
.format(filename.replace("\\", "/")))
if deleteTempFile: if deleteTempFile:
Path(filename).unlink() Path(filename).unlink()

View File

@ -81,10 +81,11 @@ class PythonInterpreter(QgsCodeInterpreter, code.InteractiveInterpreter):
except ModuleNotFoundError: except ModuleNotFoundError:
pass pass
def execCommandImpl(self, cmd): def execCommandImpl(self, cmd, show_input=True):
res = self.currentState() res = self.currentState()
self.writeCMD(cmd) if show_input:
self.writeCMD(cmd)
import webbrowser import webbrowser
version = 'master' if 'master' in Qgis.QGIS_VERSION.lower() else \ version = 'master' if 'master' in Qgis.QGIS_VERSION.lower() else \
re.findall(r'^\d.[0-9]*', Qgis.QGIS_VERSION)[0] re.findall(r'^\d.[0-9]*', Qgis.QGIS_VERSION)[0]
@ -291,3 +292,19 @@ class ShellScintilla(QgsCodeEditorPython):
def write(self, txt): def write(self, txt):
if sys.stderr: if sys.stderr:
sys.stderr.write(txt) sys.stderr.write(txt)
def runFile(self, filename):
filename = filename.replace("\\", "/")
dirname = os.path.dirname(filename)
# Append the directory of the file to the path and set __file__ to the filename
self._interpreter.execCommandImpl("sys.path.append('{0}')".format(dirname), False)
self._interpreter.execCommandImpl("__file__ = '{0}'".format(filename), False)
try:
# Run the file
self.runCommand("exec(Path('{0}').read_text())".format(filename))
finally:
# Remove the directory from the path and delete the __file__ variable
self._interpreter.execCommandImpl("del __file__", False)
self._interpreter.execCommandImpl("sys.path.remove('{0}')".format(dirname), False)