Exporting packages containing “Python Code” cells

I created a notebook with Python code cells (evaluated using External Evaluate) as can be created by typing > at the beginning of a cell. (And choosing Python for the external evaluator). I then marked these cells as initialization cells. However, I find that I can’t reliably create packages (I create packages autoamtically using the answer in https://mathematica.stackexchange.com/a/31323/45020). The python cells do become python cells in the package but they get corrupted. It wrongly breaks cells up at any double new line (this can at least be avoided) but also randomly misses text. A cell with

import scipy.optimize import numpy as np def stuff(): ... 

just becomes import scipy.optimize import numpy as def stuff(): … and thus gives a syntax error since np is missing. The original notebook file works perfectly and has no such errors.

Is there any reliable way to export? Does everyone have these issues?

Version: "12.1.1 for Linux x86 (64-bit) (June 19, 2020)"


It gets even weirder. There seems to be some randomness to it. Now I managed to (without making changes) export it correctly to a package that does not produce any errors when run from within MMA (i.e. when opening it and running all the cells.) However, when calling it from another notebook using Get I still get a syntax error. I checked and see no syntax error in the cell where it should supposedly be.


It might be related to having set up a custom virtual environment using this answer. However, everything is working perfectly in the notebook. The issues only arise when converting to a package.