Home > OS >  Switching environments within a python script
Switching environments within a python script

Time:06-01

I have a python script which needs to call the matlab engine so that I can use a code base (many funcitons) without having to rewrite a ton of code into python. Problem is the solution I found for running matlab requires an environemnt set up. I already have an environment set up to run my scripts in and I need to be able to switch between them. Can I do this with os? I am running this on a windows machine in a linux vm in a locally hosted jupyter session.

Example jmatlab https://am111.readthedocs.io/en/latest/jmatlab_install.html

Pseudocode to give you an idea of what I want to do...

os.environ["jmatlab"]
#matlab engine stuff...
os.environ["orignal_env"]

CodePudding user response:

I feel that I've answered something similar to this before, but can't find an exact fit. One can't switch a Python process mid-execution to have context-sensitive evaluation, like OP describes. However, os.system or subprocess.run could be used run the other Python code (as a separate script) inside another environment. Without a detailed mock example, we can't detail the sharing of data across the processes. But it would broadly be using conda run -n jmatlab python matlab_engine_stuff.py to run in the other environment.

Try looking into conda run (e.g., conda run --help). This answer is also loosely related, though it is about running system commands outside the Python's environment. There might be some applicable solutions for running subparts of code under separate Python 2 and 3 processes.

  • Related