Cannot run Python script using sudo
Asked Answered
P

3

11

I have a simple script which is using signalr-client-py as an external module.

from requests import Session
from signalr import Connection
import threading

When I try to run my script using the sudo python myScriptName.py I get an error:

Traceback (most recent call last):
  File "buttonEventDetectSample.py", line 3, in <module>
    from signalrManager import *
  File "/home/pi/Desktop/GitRepo/DiatAssign/Main/signalrManager.py", line 2, in <module>
    from signalr import Connection
ImportError: No module named signalr

If I run my script typing only python myScriptName.py it works perfectly fine but I need to have the sudo in front because later on in my other scripts (that use this one) I perform write operation on the File system.

I am quite new to Python and that's why I need to know how I can handle this situation. If I type pydoc modules I get a list which contains:

signalr
signalrManager

If I type pip freeze I can see there listed:

signalr-client==0.0.7
Pesach answered 13/5, 2018 at 11:32 Comment(2)
Do "sudo which python" and "which python" yield different results ?Adrenal
They both yield '/usr/bin/python'Pesach
M
18

By default sudo runs commands in different environment. You can ask sudo to preserve environment with -E switch.

sudo -E python myScriptName.py

It comes with it's own security risks. So be careful

Mordvin answered 13/5, 2018 at 11:57 Comment(1)
This one works, but I am not really sure what exactly is the issue with external package/module/library that I am using.Pesach
Q
1

You need to check where signalr is installed. sudo runs the program in the environment available to root and if signalr is not installed globally it won't be picked up. Try 'sudo pip freeze' to see what is available in the root environment.

Quadruple answered 13/5, 2018 at 11:50 Comment(2)
I can not see my module there but I believe the message of the error that I get states exactly this so it was expected. Not really sure how to persist it in my root directory. Can I copy/paste it somehow or this is wrong?Pesach
Not quite sure what you are proposing to copy/paste, nor in this context am I sure what 'my module' means as i would not expect the module you have written to show up on a pip freeze anyway. What I think you may need to do is either to 'sudo pip install signalr' or whatever package contains signalr or follow the advice in the other answer and use the '-E' switch for sudo.Quadruple
M
0

Another easy solution can be installing required packages via sudo -even they are installed before normally- instead of trying to match the paths:

sudo pip3 install <your-required-package-name>

After that you can execute the scripts via sudo.

Micrography answered 21/9, 2022 at 10:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.