[Tex/LaTex] Setting conda environment for pythontex in TexStudio


I am using Texstudio with a build configuration based on this question in order to run PythonTex and embed python code into my documents. This worked and I was able to use the \begin{pycode} and \end{pycode} successfully.

However the libraries I want to use are in a dedicated conda environment and not in the main system python. I added the --interpreter argument to my build in Texstudio such that it uses the interpreter from that environment. My build command looks like this in Texstudio:

txs:///compile | pythontex %.tex --interpreter "C:\ProgramData\Anaconda2\envs\wps_env36\python.exe" | txs:///compile | txs:///view 

Simple commands like print('hello') will work. However as soon as I try to import libraries which I know exist in this environment it returns an error. This indicates to me that although the interpreter is correctly set, other parameters necessary for the functioning of the conda environment are not.

How do I activate a conda environment such that it becomes the one pythontex is using within TexStudio?

Best Answer

You can activate the conda environment (activate.bat) and chain it (&&) with running pythontex using:

"C:\ProgramData\Anaconda2\Scripts\activate.bat" "C:\ProgramData\Anaconda2\envs\wps_env36\python.exe" && pythontex %.tex

By the way, it is generally not recommended to pollute the build chain with raw commands like you did. It's better to save this as a user command, then call it during your Build & View call.

enter image description here

To show that pythontex is in the correct environment, (on a bare test environment with pygments installed):

import sys
hello world


enter image description here

whereas my base python environment has version 3.6.7.

Related Question