I have read plenty of documentation (including this and linked references) on this, but it is simply too difficult for my simple mind: I cannot understand the logics of python import
and I usually waste plenty of time in random attempts till I reach a working permutation of settings and commands. May be this is due to the fact that I usually use PyCharm, where everything magically work. Now I am using Visual Studio Code on a remote machine and I need to ask here since I have wasted double the time I usually spend on this without reaching a permutation that works.
Using python 3 on linux (remote machine). The python interpreter is configured with a virtual environment and it does not correspond to the system level one.
I have this project. Its folder structure is mirrored in linux filesystem, i.e., prj, src, commonn, etc. are all folders.
prj
|- src
| some py files
| |- common/
| - common1.py
| - common2.py
| |- pipelines/
| - main_pipeline1.py (<- file prefixed with main_ have a __main__ entry point)
| - main_pipeline2.py
| | - other py module
| | - other py module, ... and others - some of these modules use common
|- data/ ...
|- doc/ ...
In pipeline1.py
, I have: import common.common1
. I corrected this
In what follows $[folder]
corresponds to the bash prompt, so $
stands for normal user and folder
is the current folder.
When I run pipeline1.py
as normal user (on the remote machine), first I get an error:
$[prj/src] python pipeline/pipeline1.py
ModuleNotFoundError: No module named 'common'
In order to have it working I need to add the current folder to PYTHONPATH
(that is empty). So
$[prj/src] PYTHONPATH=.
$[prj/src] python pipeline/pipeline1.py
works.
However, the previous script writes in a disk that requires root access, so the previous command needs to be run with sudo
. I cannot find a way to run it using sudo:
I tried (after reading, among others, this):
$[prj/src] sudo python pipeline/pipeline1.py
$[prj/src] sudo /path/to/env/bin/python pipeline/pipeline1.py
$[prj/src] sudo -E /path/to/env/bin/python pipeline/pipeline1.py
they all fail, all but the first because python cannot find the module common
. Even if I asked to keep the environment with -E
(so PYTHONPATH
should be kept) the import fails. All the other imports from the virtual environment (that occur before the import common
) do not fail.
In the future I need to give the code to a sys admin that might possibly not have any specific knowledge of python: I cannot ask him to set PYTHONPATH check this, check that.
In this case, how should I organize my code to have the import common
(or any other module I write) succeed? Do I really need to add PYTHONPATH=.
every time?
Is there any kind soul willing to help me? Beer after the pandemic is over.
I made a correction:
import common.common1.py --> common.common1