Ejemplo n.º 1
0
def _get_notebook_kwargs(initial_path=None, notebook_path=None):
    """Get the kwargs for calling launch_jupyter.

    :param initial_path: Path to open Jupyter in.
    :param notebook_path: Path of Jupyter notebook to open.
    """
    if initial_path is not None and notebook_path is not None:
        raise RuntimeError(
            "'initial_path' and 'notebook_path' cannot both be set.")

    if notebook_path is not None:
        if not os.path.exists(notebook_path):
            raise RuntimeError("Notebook path '%s' not found." % notebook_path)
        if not os.path.isfile(notebook_path):
            raise RuntimeError("Notebook path '%s' is not a file." %
                               notebook_path)
        notebook_path = os.path.abspath(notebook_path)

    cfg = get_config()
    timeout = _get_jupyter_timeout(cfg)

    if notebook_path is None and initial_path is None:
        initial_path = _get_notebook_path(cfg)
    if initial_path and not os.path.exists(initial_path):
        raise RuntimeError("Directory '%s' does not exist.")
    if initial_path and not os.path.isdir(initial_path):
        raise RuntimeError("Path '%s' is not a directory.")

    return {
        "initial_path": initial_path,
        "notebook_path": notebook_path,
        "timeout": timeout
    }
Ejemplo n.º 2
0
def open_logfile(*args):
    """Open the PyXLL Log file"""
    config = get_config()
    if config.has_option("LOG", "path") and config.has_option("LOG", "file"):
        path = os.path.join(config.get("LOG", "path"),
                            config.get("LOG", "file"))
        webbrowser.open("file://%s" % path)
Ejemplo n.º 3
0
def _init_notebooks():
    global _notebooks, _selected_notebook
    if _notebooks is None:
        cfg = pyxll.get_config()
        notebooks = cfg.get("NOTEBOOK", "notebooks", fallback="")
        _notebooks = [x for x in map(str.strip, notebooks.split(";")) if x]
        _notebooks.sort()
Ejemplo n.º 4
0
def get_notebook_path():
    """Return the path to open the Jupyter notebook in."""
    cfg = get_config()

    # Use the path of the active workbook if use_workbook_dir is set
    use_workbook_dir = False
    if cfg.has_option("JUPYTER", "use_workbook_dir"):
        try:
            use_workbook_dir = bool(int(cfg.get("JUPYTER", "use_workbook_dir")))
        except (ValueError, TypeError):
            _log.error("Unexpected value for JUPYTER.use_workbook_dir.")

    if use_workbook_dir:
        xl = xl_app()
        wb = xl.ActiveWorkbook
        if wb is not None and wb.FullName and os.path.exists(wb.FullName):
            return os.path.dirname(wb.FullName)

    # Otherwise use the path option
    if cfg.has_option("JUPYTER", "notebook_dir"):
        path = cfg.get("JUPYTER", "notebook_dir").strip("\"\' ")
        if os.path.exists(path):
            return os.path.normpath(path)
        _log.warning("Notebook path '%s' does not exist" % path)

    # And if that's not set use My Documents
    CSIDL_PERSONAL = 5  # My Documents
    SHGFP_TYPE_CURRENT = 0  # Get current, not default value

    buf = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH)
    ctypes.windll.shell32.SHGetFolderPathW(None, CSIDL_PERSONAL, None, SHGFP_TYPE_CURRENT, buf)
    return buf.value
Ejemplo n.º 5
0
def pyxll_logfile():
    """returns the pyxll logfile path"""
    config = pyxll.get_config()
    if config.has_option("LOG", "path") and config.has_option("LOG", "file"):
        path = os.path.join(config.get("LOG", "path"), config.get("LOG", "file"))
        return path
    return "No log path set in the PyXLL config"
Ejemplo n.º 6
0
def on_open_logfile():
    # the PyXLL config is accessed as a ConfigParser.ConfigParser object
    config = get_config()
    if config.has_option("LOG", "path") and config.has_option("LOG", "file"):
        path = os.path.join(config.get("LOG", "path"),
                            config.get("LOG", "file"))
        webbrowser.open("file://%s" % path)
Ejemplo n.º 7
0
def pyxll_logfile():
    """returns the pyxll logfile path"""
    config = pyxll.get_config()
    if config.has_option("LOG", "path") and config.has_option("LOG", "file"):
        path = os.path.join(config.get("LOG", "path"), config.get("LOG", "file"))
        return path
    return "No log path set in the PyXLL config"
Ejemplo n.º 8
0
def _get_connection_dir(app):
    """Gets the connection dir to use for the IPKernelApp"""
    connection_dir = None

    # Check the pyxll config first
    cfg = get_config()
    if cfg.has_option("JUPYTER", "runtime_dir"):
        connection_dir = cfg.get("JUPYTER", "runtime_dir")
        if not os.path.abspath(connection_dir):
            connection_dir = os.path.join(os.path.dirname(pyxll.__file__),
                                          connection_dir)

    # If not set in the pyxll config use the default from the kernel
    if not connection_dir:
        connection_dir = app.connection_dir

    # If Excel is installed as a UWP then AppData will appear as a different folder when the
    # child Python process is run so use a different path.
    excel_path = _get_excel_path()
    if "WindowsApps" in re.split(r"[/\\]+", excel_path):
        _log.debug("Excel looks like a UWP app.")
        if "AppData" in re.split(r"[/\\]+", connection_dir):
            connection_dir = os.path.join(os.path.dirname(pyxll.__file__),
                                          ".jupyter", "runtime")
            _log.warning(
                "Jupyter's runtime directory is in AppData but Excel is installed as a UWP. "
            )
            _log.warning(f"{connection_dir} will be used instead.")
            _log.warning(
                "Set 'runtime_dir' in the '[JUPYTER]' section of your pyxll.cfg to change this directory."
            )

    return connection_dir
Ejemplo n.º 9
0
def open_logfile(control):
    """Opens the PyXLL log file"""
    config = get_config()
    if not config.has_option("LOG", "path") or not config.has_option(
            "LOG", "file"):
        raise Exception("Log file not found")

    path = os.path.join(config.get("LOG", "path"), config.get("LOG", "file"))
    webbrowser.open("file://%s" % path)
Ejemplo n.º 10
0
def on_open(import_info):
    """Start the remote kernel when Excel starts up, or PyXLL is reloaded.
    """
    cfg = get_config()
    start_on_open = bool(int(cfg.get("NOTEBOOK", "start_on_open", fallback=0)))
    if start_on_open:
        km = KernelManager.instance()
        loop = get_event_loop()
        f = asyncio.run_coroutine_threadsafe(km.start_all_kernels(), loop)
        f.result()
Ejemplo n.º 11
0
def _get_qt_packages():
    """Return a tuple of Qt packages to try importing."""
    qt_pkgs = "pyside2", "pyqt5"

    cfg = pyxll.get_config()
    if cfg.has_option("JUPYTER", "qt"):
        qt_pkg = cfg.get("JUPYTER", "qt").strip().lower()
        _log.debug("pyxll_jupyter:Qt package specified as '%s'." % qt_pkg)
        if qt_pkg not in qt_pkgs:
            raise RuntimeError("Unsupported Qt package specified: '%s'" %
                               qt_pkg)
        return qt_pkg,

    return qt_pkgs
Ejemplo n.º 12
0
def on_open(import_info):
    """Fetches and registers any remote Anvil functions"""
    cfg = get_config()
    token = cfg.get("ANVIL", "token", fallback="")
    if not token:
        _log.warning(
            "No Anvil token found. No remote functions will be available.")
        return

    # Connect to the anvil server and register any functions
    anvil.server.connect(token)

    xl_funcs = anvil.server.call("pyxll.get_xl_funcs")
    if xl_funcs:
        register_xl_funcs(xl_funcs)
        rebind()
Ejemplo n.º 13
0
def open_jupyter_notebook(*args):
    """Ribbon action function for opening the Jupyter notebook
    browser control.
    """
    from pyxll import create_ctp

    # Create the Qt Application
    app = _get_qt_app()

    # The create the widget and add it as an Excel CTP
    cfg = get_config()
    path = _get_notebook_path(cfg)
    timeout = _get_jupyter_timeout(cfg)
    widget = JupyterQtWidget(initial_path=path, timeout=timeout)

    create_ctp(widget, width=800)
Ejemplo n.º 14
0
def ribbon():
    """Entry point for getting the pyxll ribbon file.
    Returns a list of (filename, data) tuples.
    """
    cfg = get_config()

    disable_ribbon = False
    if cfg.has_option("JUPYTER", "disable_ribbon"):
        try:
            disable_ribbon = bool(int(cfg.get("JUPYTER", "disable_ribbon")))
        except (ValueError, TypeError):
            _log.error("Unexpected value for JUPYTER.disable_ribbon.")

    if disable_ribbon:
        return []

    ribbon = pkg_resources.resource_string(__name__, "resources/ribbon.xml")
    return [(None, ribbon)]
Ejemplo n.º 15
0
def open_jupyter_notebook(*args, initial_path=None, notebook_path=None):
    """Ribbon action function for opening the Jupyter notebook
    browser control.

    :param initial_path: Path to open Jupyter in.
    :param notebook_path: Path of Jupyter notebook to open.
    """
    from pyxll import create_ctp

    if initial_path is not None and notebook_path is not None:
        raise RuntimeError(
            "'initial_path' and 'notebook_path' cannot both be set.")

    if notebook_path is not None:
        if not os.path.exists(notebook_path):
            raise RuntimeError("Notebook path '%s' not found." % notebook_path)
        if not os.path.isfile(notebook_path):
            raise RuntimeError("Notebook path '%s' is not a file." %
                               notebook_path)
        notebook_path = os.path.abspath(notebook_path)

    # Create the Qt Application
    app = _get_qt_app()

    # The create the widget and add it as an Excel CTP
    cfg = get_config()
    timeout = _get_jupyter_timeout(cfg)

    if notebook_path is None and initial_path is None:
        initial_path = _get_notebook_path(cfg)
    if initial_path and not os.path.exists(initial_path):
        raise RuntimeError("Directory '%s' does not exist.")
    if initial_path and not os.path.isdir(initial_path):
        raise RuntimeError("Path '%s' is not a directory.")

    widget = JupyterQtWidget(initial_path=initial_path,
                             timeout=timeout,
                             notebook_path=notebook_path)

    create_ctp(widget, width=800)
Ejemplo n.º 16
0
"""
import errno
import logging
import os

from stevedore import extension

from pyxll import get_config
from .ribbon_synthesizer import RibbonSynthesizer

logger = logging.getLogger(__name__)

# Keyword args to pass to plugin initializers
invoke_kwds = {}

config = dict(get_config().items('PYXLL'))
default_ribbon_path = config.get('default_ribbon', '')
ribbon_path = config.get('ribbon', '')

should_make_ribbon = (default_ribbon_path and ribbon_path
                      and default_ribbon_path != ribbon_path)
ribbon_synthesizer = RibbonSynthesizer.from_file(default_ribbon_path)

if should_make_ribbon:
    invoke_kwds['submit_ribbon_tab'] = ribbon_synthesizer.submit_ribbon_tab
else:
    logger.info("The ribbon will not be modified because your config does"
                " not define both PYXLL::ribbon and PYXLL::default_ribbon")

extension_manager = extension.ExtensionManager(
    namespace='pyxll.extensions',
Ejemplo n.º 17
0
"""
import errno
import logging
import os

from stevedore import extension

from pyxll import get_config
from .ribbon_synthesizer import RibbonSynthesizer

logger = logging.getLogger(__name__)

# Keyword args to pass to plugin initializers
invoke_kwds = {}

config = dict(get_config().items('PYXLL'))
default_ribbon_path = config.get('default_ribbon', '')
ribbon_path = config.get('ribbon', '')

should_make_ribbon = (default_ribbon_path and ribbon_path and
                      default_ribbon_path != ribbon_path)
ribbon_synthesizer = RibbonSynthesizer.from_file(default_ribbon_path)

if should_make_ribbon:
    invoke_kwds['submit_ribbon_tab'] = ribbon_synthesizer.submit_ribbon_tab
else:
    logger.info("The ribbon will not be modified because your config does"
                " not define both PYXLL::ribbon and PYXLL::default_ribbon")

extension_manager = extension.ExtensionManager(
    namespace='pyxll.extensions',
Ejemplo n.º 18
0
 def instance(cls):
     if cls._instance is None:
         cfg = get_config()
         cls._instance = cls(cfg)
     return cls._instance
Ejemplo n.º 19
0
def on_open_logfile():
    # the PyXLL config is accessed as a ConfigParser.ConfigParser object
    config = get_config()
    if config.has_option("LOG", "path") and config.has_option("LOG", "file"):
        path = os.path.join(config.get("LOG", "path"), config.get("LOG", "file"))
        webbrowser.open("file://%s" % path)
Ejemplo n.º 20
0
def Simulate():
    global num_of_sim 
    global op  
    global num_of_inp
    global iter_num
    global current_inp
    global inpcell
    global output_flag
    global usr_selection
    global inparraycell
    global formstr
    global arrayvals
    global simcomplete
    global inp
    
    xlcCalculateNow()
    xlcCalculateDocument()
    if not output_flag:
        xlcAlert("Select a output cell. If selected, click reload")
        return
#     
    checkMIArray=False
    win32com.client.gencache.Rebuild()
    xl_window = get_active_object()
    xl_app = win32com.client.Dispatch(xl_window).Application
    xl_app.Calculation=xlCalculationManual
#     xl_app = win32com.client.GetActiveObject("Excel.Application")
#     win32com.client.gencache.EnsureDispatch(xl_app)
    
    num_of_sim = 0
    if ((inpcell is not None) and formstr == str(inpcell.formula) ): 
        checkMIArray=True
#         xlcAlert('inside looop:'+ str(inp).strip('[]'))
        rect = inpcell.rect
#         xlcAlert(inpcell.address)
#         xlcAlert(str(rect.first_row))
#         xlcAlert(str(rect.first_col))
        selection = xl_app.ActiveSheet.Cells(int(rect.first_row)+1,int(rect.first_col)+1)
#         selection.value = 100
#     inpcell.value = 100
#     xlcAlert("click OK")
    
    app1 = QApplication(sys.argv)
    form = Dialog.popup()
    app1.exec_()
    num_of_sim = int(Dialog.retval())
    usr_selection = str(Dialog.retsel())
    writeFG = Dialog.writeflag()
    if num_of_sim > 0:
        current_inp =1
#         xlcAlert(str(num_of_sim))
        start = time.time()
        op=None
        op = zeros((num_of_inp,num_of_sim))        
        xl_app.ScreenUpdating = False
        xl_app.DisplayStatusBar = False
        xl_app.EnableEvents = False
        for j in range(num_of_inp):
            current_inp = j
            if (checkMIArray):
                selection.Value = inp[current_inp]
            for i in range(num_of_sim):
                iter_num = i
                xlcCalculateDocument()
        end = time.time()
        xl_app.ScreenUpdating = True
        xl_app.DisplayStatusBar = True
        xl_app.EnableEvents = True
        current_inp = 0
        simcomplete= True
#         selection.value = inp[current_inp]
#         selection.Formula = inpcell.formula
        if checkMIArray:    
            fstr = '=MiInput(' + inparraycell.address + ')'
            selection.Formula = fstr
#         xlcAlert(str(checkMIArray))
        if not checkMIArray:
            inp = [0]
        UI.draw(op, inp,usr_selection)
        # Store data in a CSV format
        if checkMIArray:
            popupstr = ''
            for idx,inpvalue in enumerate(inp):
                tupleop = None
                tupleop = tuple(op[idx])
                datastr = "data" + str(idx)
                xl_app.ActiveWorkbook.Names.Add(datastr,tupleop,False)
                popupstr = popupstr + "Output variable for Input " + str(inpvalue) + "is: "+str(datastr) + "\n"
            popupstr = popupstr + "You can use all the excel statistical functions on these variables"
            xlcAlert(popupstr) 
        else:
            tupleop = tuple(op)
            xl_app.ActiveWorkbook.Names.Add("data",tupleop,False)
            xlcAlert("Your Output Variable is 'data'" + "\n" + "You can use all the excel statistical functions on this variable")
        if writeFG:
            config = get_config()
            config.read('pyxll.cfg')
            dir_path = config.get('LOG','path')
            xlcAlert("Data stored at "+str(dir_path))
            file_name = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
            if checkMIArray:
#                 xlcAlert(str(len(op[1])))
                for idx,inpvalue in enumerate(inp):
                    file_name1 = file_name +"-input "+str(inpvalue) +'.csv'
                    if os.path.exists(dir_path): 
                        myfile = open(os.path.join(dir_path, file_name1), 'wb')
                        wr = csv.writer(myfile, dialect='excel')
                        wr.writerow(op[idx])
            else:
                if os.path.exists(dir_path):
                    file_name = file_name + '.csv' 
                    myfile = open(os.path.join(dir_path, file_name), 'wb')
                    wr = csv.writer(myfile, dialect='excel')
                    wr.writerows(op)