Skip to content

Commit

Permalink
Clear python variables in script window when executing whole script
Browse files Browse the repository at this point in the history
Refs #9270
  • Loading branch information
martyngigg committed May 7, 2014
1 parent 9d76192 commit 6c861ad
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 3 deletions.
17 changes: 15 additions & 2 deletions Code/Mantid/MantidPlot/src/PythonScript.cpp
Expand Up @@ -417,6 +417,19 @@ void PythonScript::setContext(QObject *context)
setQObject(context, "self");
}

/**
* Clears the current set of local variables and resets
* the dictionary context back to the default set
*/
void PythonScript::clearLocals()
{
GlobalInterpreterLock pythonlock;

Py_XDECREF(localDict); //clear up any previous dictionary
PyObject *pymodule = PyImport_AddModule("__main__");
localDict = PyDict_Copy(PyModule_GetDict(pymodule));
}

/**
* Sets the context for the script and if name points to a file then
* sets the __file__ variable
Expand All @@ -425,9 +438,9 @@ void PythonScript::setContext(QObject *context)
*/
void PythonScript::initialize(const QString & name, QObject *context)
{
clearLocals(); // holds and releases GIL

GlobalInterpreterLock pythonlock;
PyObject *pymodule = PyImport_AddModule("__main__");
localDict = PyDict_Copy(PyModule_GetDict(pymodule));
PythonScript::setIdentifier(name);
setContext(context);
}
Expand Down
2 changes: 2 additions & 0 deletions Code/Mantid/MantidPlot/src/PythonScript.h
Expand Up @@ -93,6 +93,8 @@ class PythonScript : public Script, MantidQt::API::WorkspaceObserver
bool setDouble(double val, const char* name);
/// Set the context for this script
void setContext(QObject *context);
/// Resets the local dictionary to the defaults
void clearLocals();

private:
/// Helper class to ensure the sys.path variable is updated correctly
Expand Down
1 change: 1 addition & 0 deletions Code/Mantid/MantidPlot/src/Script.h
Expand Up @@ -118,6 +118,7 @@ public slots:
virtual bool setQObject(QObject*, const char*) { return false; }
virtual bool setInt(int, const char*) { return false; }
virtual bool setDouble(double, const char*) { return false; }
virtual void clearLocals() {}

signals:
/// A signal defining when this script has started executing
Expand Down
4 changes: 3 additions & 1 deletion Code/Mantid/MantidPlot/src/ScriptFileInterpreter.cpp
Expand Up @@ -225,10 +225,12 @@ void ScriptFileInterpreter::showFindReplaceDialog()
}

/**
* Execute the whole script in the editor.
* Execute the whole script in the editor. Always clears the contents of the
* local variable dictionary first.
*/
void ScriptFileInterpreter::executeAll(const Script::ExecutionMode mode)
{
m_runner->clearLocals();
executeCode(m_editor->text(), mode);
}

Expand Down

0 comments on commit 6c861ad

Please sign in to comment.