Closed GlidingRaven closed 1 year ago
Hi @GlidingRaven,
The issue here is related to argparse and sys.argv
. Hydra's @hydra.main
function relies on argparse to read from sys.argv
, and in Jupyter notebooks this is problematic.
I'd recommend using the compose
API when working with Jupyter. See this example app using a Jupyter notebook.
It would also be possible to manually patch sys.argv
before calling my_app
, though this is not so elegant.
For those who want to write scripts with Hydra that work both inside Ipython and in the terminal, the following should work without sacrificing any CLI functionality:
import hydra
from omegaconf import DictConfig, OmegaConf
from hydra import initialize, compose
def is_ipython():
try:
shell = get_ipython().__class__.__name__ #DO NOT IMPORT get_ipython
return True
except NameError:
return False
def run_with_config(main_fn, cfg_name = "default_config"):
if is_ipython():
with initialize(".", None):
cfg = compose(cfg_name)
main_fn(cfg)
else:
decorator = hydra.main(version_base=None, config_path=".",
config_name=cfg_name)
decorator(main_fn)()
def main(cfg: DictConfig):
print(OmegaConf.to_yaml(cfg))
if __name__ == "__main__":
run_with_config(main)
Note that the config_path
passed to hydra.main
has to be relative to the location of the main_fn
, whereas the config_path
passed to initialize
is relative to the script where run_with_config
is defined. This becomes relevant if you refactor the non-main functions into another script.
Try this: import sys sys.argv=['self.py']
(Source: https://stackoverflow.com/questions/13657199/use-sys-argv-inside-ipython3-notebook)
🐛 Bug (?)
Description
I can't reproduce the Basic example on Jupyter notebook.
Checklist
To reproduce
Config: (conf/config.yaml)
Run a cell:
Output:
System information
Additional context
Is it possible to run the Hydra on Jupyter?