Commit 8550342f authored by Benoit Formet's avatar Benoit Formet
Browse files

user_load_script: add support for export_global="user"

parent 7ca8016e
......@@ -481,32 +481,31 @@ class Session:
def user_script_load(self, scriptname=None, export_global=False):
"""
load a script and export all public (= not starting with _)
objects and functions to the returned namespace.
(or optionnaly can export to the current environment.
Use with caution: risk of overwriting important stuff)
(exceptions are printed but not thrown)
objects and functions to current environment or to a namespace.
(exceptions are printed but not thrown, execution is stopped)
Args:
scriptname: the python file to load (can be an absolute path or relative to script_homedir)
export_global (default: False): whether to export to session or return a namespace
scriptname: the python file to load (script path can be absolute relative to script_homedir)
Optional args:
export_global=False (default): return a namespace
export_global=True: export objects to session env dict
export_global="user": export objects to "user" namespace in session env dict (eg. user.myfunc())
"""
return self._user_script_exec(
scriptname, return_namespace=True, export_global=export_global
scriptname, load=True, export_global=export_global
)
def user_script_run(self, scriptname=None):
"""
Execute a script without exporting objects or functions to current environment.
(exceptions are printed but not thrown)
(exceptions are printed but not thrown, execution is stopped)
Args:
scriptname: the python file to run (can be an absolute path or relative to script_homedir)
scriptname: the python file to run (script path can be absolute or relative to script_homedir)
"""
self._user_script_exec(scriptname, return_namespace=False)
self._user_script_exec(scriptname, load=False)
def _user_script_exec(
self, scriptname, return_namespace=False, export_global=False
):
def _user_script_exec(self, scriptname, load=False, export_global=False):
if not scriptname:
self.user_script_list()
return
......@@ -533,7 +532,7 @@ class Session:
except Exception:
raise RuntimeError(f"Failed to read [{filepath}] !")
if return_namespace is True:
if load is True:
print(f"Loading [{filepath}]...")
else:
print(f"Running [{filepath}]...")
......@@ -547,13 +546,18 @@ class Session:
except Exception:
sys.excepthook(*sys.exc_info())
# case: run file
if not load:
return
# case: export to global env dict
if export_global is True:
for k in globals_dict.keys():
if k.startswith("_"):
continue
self.env_dict[k] = globals_dict[k]
elif return_namespace is True:
else:
env_dict = dict()
for k in c_code.co_names:
if k.startswith("_"):
......@@ -561,10 +565,14 @@ class Session:
if k not in globals_dict:
continue
env_dict[k] = globals_dict[k]
return SimpleNamespace(**env_dict)
ns = SimpleNamespace(**env_dict)
else:
return None
if isinstance(export_global, str):
# case: export to given namespace in env dict
self.env_dict[export_global] = ns
else:
# case: export_global is False, return the namespace
return ns
def setup(self, env_dict=None, verbose=False):
if get_current_session() is None:
......
......@@ -4,7 +4,7 @@
Python files from a local directory can be executed in a bliss session using the functions
`user_script_load(<file_name>)` or `user_script_run(<file_name>)`.
All commands in the file are then executed. And each subsequent call re-execute the commands again.
All commands in the file are executed. And each subsequent call re-execute the commands again.
A preferred directory can be set with the function `user_script_homedir()` and `user_script_list()` will display the python scripts available from this directory.
......@@ -14,26 +14,31 @@ A preferred directory can be set with the function `user_script_homedir()` and `
!!! info "Error handling"
In case of error, the functions `user_script_load()` and `user_script_run()` catch
and display exceptions, but do not prevent the rest of the script from executing.
and display exceptions, and the script execution is stopped. Exceptions are printed not thrown.
## User script functions
### Run script
`user_script_run()` function executes all commands in the file. Nothing is exported to the current environment.
`user_script_run(script_name)` function executes all commands in the file. Nothing is exported to the current environment.
Argument:
* `script_name`: the python file to execute
* `script_name`: the python file to execute (relative or absolute path)
### Load script
`user_script_load()` function executes all commands in the file and export all symbols.
`user_script_load(script_name)` function executes all commands in the file and export all symbols.
Arguments:
Argument:
* `script_name`: the python file to execute (relative or absolute path)
Optional argument:
* `script_name`: the python file to execute
* `export_global` (optional, default is False): export to current environment or return a namespace
* `export_global=False` (default): return a namespace
* `export_global=True`: export to current environment
* `export_global="user"`: export a "user" namespace to current environment ()
Return value:
......@@ -59,7 +64,7 @@ Return value:
There is no predefined user script directory by default.
If none is set, you can still load scripts by giving an absolute path.
You can specify a default directory by adding this line to a session yaml configuration file:
You can specify a default directory by adding this line to a session .yml configuration file:
`default-userscript-dir: <absolute_path_to_dir>`
......@@ -97,3 +102,29 @@ Aligning spectrometer for energy 7.5 ...
Spectrometer is aligned :)
DEMO [3]:
```
alternative usage:
```python
DEMO [1]: user_script_load('demo', export_global="demo")
Loading [/path/to/demo.py]...
[loading script]: align_spectrometer()
DEMO [2]:
DEMO [2]: demo.align_spectrometer(energy=7.5)
Aligning spectrometer for energy 7.5 ...
Spectrometer is aligned :)
DEMO [3]:
```
or
```python
DEMO [1]: user_script_load('demo', export_global=True)
Loading [/path/to/demo.py]...
[loading script]: align_spectrometer()
DEMO [2]:
DEMO [2]: align_spectrometer(energy=7.5)
Aligning spectrometer for energy 7.5 ...
Spectrometer is aligned :)
DEMO [3]:
```
......@@ -138,8 +138,12 @@ def test_user_script(session4, capsys):
user_script_load("sessions/scripts/script3", export_global=True)
assert "toto" in session4.env_dict
expected_symbols = ["ascan", "time", "test1", "a"]
ns = user_script_load("sessions/subdir/scripts/simple_script")
assert list(ns.__dict__) == ["ascan", "time", "test1", "a"]
assert list(ns.__dict__) == expected_symbols
user_script_load("sessions/subdir/scripts/simple_script", export_global="user_ns")
assert list(session4.env_dict["user_ns"].__dict__) == expected_symbols
def test_prdef(session2, capsys):
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment