0

Let's say I've installed torch using pip3 in my user1's account.

user1@desktop:~$ pip3 show torch
Name: torch
Version: 1.11.0
Summary: Tensors and Dynamic neural networks in Python with strong GPU acceleration
Home-page: https://pytorch.org/
Author: PyTorch Team
Author-email: packages@pytorch.org
License: BSD-3
Location: /home/user1/.local/lib/python3.8/site-packages
Requires: typing-extensions
Required-by: ogb, pytorch-lightning, torchaudio, torchmetrics, torchvision

As can be seen above, pip3-installed packages' location is /home/user1/.local/lib/python3.8/site-packages.

Now, say that I want to run some python file using sudo privilege. (Assume that I can pass along the correct password when using sudo privilege.) In this case, however, it returns ModuleNotFoundError since torch is installed in my user1's account, not in root user's.

user1@desktop:~$ sudo python3 toy_example.py
Traceback (most recent call last):
  File "toy_example.py", line 1, in <module>
    import torch
ModuleNotFoundError: No module named 'torch'

When I attempt to run certain file with sudo privilege, how can I link python packages installed in ordinary user's account? (e.g., torch, which is installed in /home/user1/.local/lib/python3.8/site-packages in the above example) I think it would be possible if I fix some environment variables, but couldn't figure it out.

SHM
  • 61
  • 1
  • 8
  • Try `which python3` in user1's previlige, and run `sudo ` where is result of first command. – minolee Jul 08 '22 at 06:55
  • @minolee Well it doesn't work, since result of `which python3` is same when ran from user1 and from root. Both results are `/usr/bin/python3`. – SHM Jul 08 '22 at 07:25
  • Maybe https://stackoverflow.com/questions/4580101/python-add-pythonpath-during-command-line-module-run this answer would help? `sudo PYTHONPATH=/home/user1/.local/lib/python3.8/site-packages python3 toy_example.py` – minolee Jul 08 '22 at 08:20
  • @minolee The command works. You've just saved so much time for me. Thanks. – SHM Jul 08 '22 at 08:40

1 Answers1

0

@minolee 's comment solved the issue. The following command works fine for me.

sudo PYTHONPATH=/home/user1/.local/lib/python3.8/site-packages python3 toy_example.py

Visit Python - add PYTHONPATH during command line module run for more help.

SHM
  • 61
  • 1
  • 8