简体   繁体   English

无法使用 sudo 运行 Python 脚本

[英]Cannot run Python script using sudo

I have a simple script which is using signalr-client-py as an external module.我有一个简单的脚本,它使用signalr-client-py作为外部模块。

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:当我尝试使用sudo python myScriptName.py运行我的脚本时,我收到一个错误:

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.如果我只输入python myScriptName.py运行我的脚本,它工作得非常好,但我需要在前面有sudo ,因为稍后在我的其他脚本(使用这个脚本)中我在文件系统上执行写操作。

I am quite new to Python and that's why I need to know how I can handle this situation.我对 Python 很陌生,这就是为什么我需要知道如何处理这种情况。 If I type pydoc modules I get a list which contains:如果我键入pydoc modules ,我会得到一个列表,其中包含:

signalr
signalrManager

If I type pip freeze I can see there listed:如果我输入pip freeze我可以看到列出:

signalr-client==0.0.7

By default sudo runs commands in different environment.默认情况下 sudo 在不同的环境中运行命令。 You can ask sudo to preserve environment with -E switch.您可以使用-E开关要求 sudo 保护环境。

sudo -E python myScriptName.py

It comes with it's own security risks.它带有自己的安全风险。 So be careful所以要小心

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. sudo 在 root 可用的环境中运行程序,如果没有全局安装 signalr,它将不会被选中。 Try 'sudo pip freeze' to see what is available in the root environment.尝试“sudo pip freeze”以查看根环境中可用的内容。

Another easy solution can be installing required packages via sudo instead of trying to match the paths:另一个简单的解决方案是通过sudo安装所需的包,而不是尝试匹配路径:

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

After that you can execute the scripts via sudo .之后,您可以通过sudo执行脚本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM