简体   繁体   English

删除sudo以运行python脚本

[英]Remove sudo to run python script

Every time that I need to run my python program with: 每当我需要使用以下命令运行python程序时:

python my_program.py

I get some error saying that some import was not found. 我收到一些错误,指出未找到某些导入。

Some error like this: 这样的错误:

Traceback (most recent call last):
  File "graphic.py", line 1, in <module>
    import matplotlib.pyplot as plt
ImportError: No module named 'matplotlib'

Than I run: 比我跑:

sudo python my_program.py

And every thing works just fine. 一切都很好。 How do I remove the sudo command to run my python codes? 如何删除sudo命令以运行python代码?

ImportError: No module named 'matplotlib' happens when your Python doesn't find the module. ImportError: No module named 'matplotlib'当您的Python找不到模块时,不会发生ImportError: No module named 'matplotlib'的模块。 sudo changes the enviornment variables; sudo更改环境变量; That's why. 这就是为什么。

To fix this, locate where matplotlib is installed in your computer, and verify the folder is part of your sys.path . 要解决此问题,请在您的计算机上找到matplotlib的安装位置,并确认该文件夹是sys.path一部分。

import sys
sys.path
['C:\\Python27\\tests', ..., ...]

Then you've two options: insert that path from your script, ie adding a line such import sys; sys.path.append(<folder>) 然后,您有两个选择:从脚本中插入该路径,即添加一行诸如import sys; sys.path.append(<folder>)的行import sys; sys.path.append(<folder>) import sys; sys.path.append(<folder>) or configure PYTHONPATH env variable under your user appending the folder to the path. import sys; sys.path.append(<folder>)或在用户下配置PYTHONPATH env变量,将文件夹附加到路径。

PYTHONPATH env variable gets loaded to sys.path on startup. PYTHONPATH env变量在启动时被加载到sys.path中。

Best solution to me is a general workflow for all projects: use virtualenviroment] 1 . 最好的解决办法我是所有项目的一般工作流程:使用virtualenviroment] 1

sudo pip3 install virtualenv
virtualenv myenv
source mynenv/bin/activate

Then you should install your libraries again with pip and they will be installed in your virtualenviroment, isolated from everything else. 然后,您应该使用pip再次安装您的库,它们将被安装在您的虚拟环境中,与其他所有事物隔离。

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

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