Skip to content

Commit a1a43e5

Browse files
committedMar 3, 2023
Fixes #49191 make "__file__" available to scripts
1 parent 08c7d66 commit a1a43e5

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed
 

‎python/console/console_editor.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -324,8 +324,8 @@ def runScriptCode(self):
324324
filename = self.createTempFile()
325325
deleteTempFile = True
326326

327-
self.pythonconsole.shell.runCommand("exec(Path('{0}').read_text())"
328-
.format(filename.replace("\\", "/")))
327+
self.pythonconsole.shell.runFile(filename)
328+
329329
if deleteTempFile:
330330
Path(filename).unlink()
331331

‎python/console/console_sci.py

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,10 +81,11 @@ def __init__(self):
8181
except ModuleNotFoundError:
8282
pass
8383

84-
def execCommandImpl(self, cmd):
84+
def execCommandImpl(self, cmd, show_input=True):
8585
res = self.currentState()
8686

87-
self.writeCMD(cmd)
87+
if show_input:
88+
self.writeCMD(cmd)
8889
import webbrowser
8990
version = 'master' if 'master' in Qgis.QGIS_VERSION.lower() else \
9091
re.findall(r'^\d.[0-9]*', Qgis.QGIS_VERSION)[0]
@@ -291,3 +292,19 @@ def entered(self):
291292
def write(self, txt):
292293
if sys.stderr:
293294
sys.stderr.write(txt)
295+
296+
def runFile(self, filename):
297+
filename = filename.replace("\\", "/")
298+
dirname = os.path.dirname(filename)
299+
300+
# Append the directory of the file to the path and set __file__ to the filename
301+
self._interpreter.execCommandImpl("sys.path.append('{0}')".format(dirname), False)
302+
self._interpreter.execCommandImpl("__file__ = '{0}'".format(filename), False)
303+
304+
try:
305+
# Run the file
306+
self.runCommand("exec(Path('{0}').read_text())".format(filename))
307+
finally:
308+
# Remove the directory from the path and delete the __file__ variable
309+
self._interpreter.execCommandImpl("del __file__", False)
310+
self._interpreter.execCommandImpl("sys.path.remove('{0}')".format(dirname), False)

0 commit comments

Comments
 (0)
Please sign in to comment.