标签归档:installation

安装Graphviz 2.38后,“ RuntimeError:确保Graphviz可执行文件在系统路径上”

问题:安装Graphviz 2.38后,“ RuntimeError:确保Graphviz可执行文件在系统路径上”

我下载了Graphviz 2.38MSI版本并安装在文件夹下C:\Python34,然后运行pip install Graphviz,一切顺利。在系统的路径中,我添加了C:\Python34\bin。在尝试在线运行测试脚本时filename=dot.render(filename='test'),我收到一条消息

 RuntimeError: failed to execute ['dot', '-Tpdf', '-O', 'test'], make sure the Graphviz executables are on your systems' path

我试图"C:\Python34\bin\dot.exe"输入系统的路径,但是它没有用,甚至创建了一个"GRAPHVIZ_DOT"带有value 的新环境变量"C:\Python34\bin\dot.exe",但仍然没有用。我尝试卸载Graphviz和pip uninstall graphviz,然后重新安装并再次进行pip安装,但是没有任何效果。

整个回溯消息是:

Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\graphviz\files.py", line 220, in render
    proc = subprocess.Popen(cmd, startupinfo=STARTUPINFO)
  File "C:\Python34\lib\subprocess.py", line 859, in __init__
    restore_signals, start_new_session)
  File "C:\Python34\lib\subprocess.py", line 1112, in _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Documents\Kissmetrics\curves and lines\eventNodes.py", line 56, in <module>
    filename=dot.render(filename='test')
  File "C:\Python34\lib\site-packages\graphviz\files.py", line 225, in render
    'are on your systems\' path' % cmd)
RuntimeError: failed to execute ['dot', '-Tpdf', '-O', 'test'], make sure the Graphviz executables are on your systems' path

有人有经验吗?

I downloaded Graphviz 2.38 MSI version and installed under folder C:\Python34, then I run pip install Graphviz, everything went well. In system’s path I added C:\Python34\bin. When I tried to run a test script, in line filename=dot.render(filename='test'), I got a message

 RuntimeError: failed to execute ['dot', '-Tpdf', '-O', 'test'], make sure the Graphviz executables are on your systems' path

I tried to put "C:\Python34\bin\dot.exe" in system’s path, but it didn’t work, and I even created a new environment variable "GRAPHVIZ_DOT" with value "C:\Python34\bin\dot.exe", still not working. I tried to uninstall Graphviz and pip uninstall graphviz, then reinstall it and pip install again, but nothing works.

The whole traceback message is:

Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\graphviz\files.py", line 220, in render
    proc = subprocess.Popen(cmd, startupinfo=STARTUPINFO)
  File "C:\Python34\lib\subprocess.py", line 859, in __init__
    restore_signals, start_new_session)
  File "C:\Python34\lib\subprocess.py", line 1112, in _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Documents\Kissmetrics\curves and lines\eventNodes.py", line 56, in <module>
    filename=dot.render(filename='test')
  File "C:\Python34\lib\site-packages\graphviz\files.py", line 225, in render
    'are on your systems\' path' % cmd)
RuntimeError: failed to execute ['dot', '-Tpdf', '-O', 'test'], make sure the Graphviz executables are on your systems' path

Does anybody have any experience with it?


回答 0

import os
os.environ["PATH"] += os.pathsep + 'D:/Program Files (x86)/Graphviz2.38/bin/'

在Windows中,只需在开头添加这两行,其中“ D:/ Program Files(x86)/Graphviz2.38/bin/”将替换为bin文件所在的地址。

那解决了问题。

import os
os.environ["PATH"] += os.pathsep + 'D:/Program Files (x86)/Graphviz2.38/bin/'

In windows just add these 2 lines in the beginning, where ‘D:/Program Files (x86)/Graphviz2.38/bin/’ is replaced by the address of where your bin file is.

That solves the problem.


回答 1

您应该在系统中安装graphviz软件包(而不仅仅是python软件包)。在Ubuntu上,您应该尝试:

sudo apt-get install graphviz

You should install the graphviz package in your system (not just the python package). On Ubuntu you should try:

sudo apt-get install graphviz

回答 2

这是我在MAC上为我解决的问题

  brew install graphviz

This one solved the problem for me on MAC:

  brew install graphviz

回答 3

对于Windows:

  1. 从以下位置安装Windows软件包:https : //graphviz.gitlab.io/_pages/Download/Download_windows.html
  2. 安装python graphviz
  3. 添加C:\Program Files (x86)\Graphviz2.38\bin到用户路径
  4. 添加C:\Program Files (x86)\Graphviz2.38\bin\dot.exe到系统路径

这对我有用!

For Windows:

  1. Install windows package from: https://graphviz.gitlab.io/_pages/Download/Download_windows.html
  2. Install python graphviz package
  3. Add C:\Program Files (x86)\Graphviz2.38\bin to User path
  4. Add C:\Program Files (x86)\Graphviz2.38\bin\dot.exe to System Path

This worked for me!


回答 4

尝试使用:

conda install python-graphviz

如果使用,graphviz可执行文件与conda目录位于不同的路径pip install graphviz

Try using:

conda install python-graphviz

The graphviz executable sit on a different path from your conda directory, if you use pip install graphviz.


回答 5

OSX Sierra,Python 2.7,Graphviz 2.38

使用pip install graphvizconda install graphviz解决了该问题。

pip只得到与您相同的路径问题,并且conda只得到导入错误。

OSX Sierra, Python 2.7, Graphviz 2.38

Using pip install graphviz and conda install graphviz BOTH resolves the problem.

pip only gets path problem same as yours and conda only gets import error.


回答 6

只需将以下内容添加到 Windows上的环境变量(系统)路径

C:\ Program档案(x86)\ Graphviz2.38 \ bin

在那里,您可以找到 .exe文件

如果不行

在您的程序文件中而不是python lib中找到Graphviz2.38 / bin文件夹

然后,添加到您的PATH

找到存在.exe文件的文件夹很重要

Just add below to your Environmental Variable(system) PATH on Windows

C:\Program Files (x86)\Graphviz2.38\bin

there, you can find .exe files

If not work

Find Graphviz2.38/bin folder in your Program Files not in python lib

Then, add to your PATH

It’s important to find a folder where .exe files exist


回答 7

步骤1:安装Graphviz二进制文件

视窗:

  1. http://www.graphviz.org/download/下载Graphviz
  2. 在下面添加到PATH环境变量中(提及已安装的graphviz版本):
    • C:\ Program档案(x86)\ Graphviz2.38 \ bin
    • C:\ Program Files(x86)\ Graphviz2.38 \ bin \ dot.exe
  3. 关闭所有打开的Juypter笔记本和命令提示符
  4. 重新启动Jupyter / cmd提示并测试

Linux:

  1. sudo apt-get更新
  2. 须藤apt-get install graphviz
  3. 或从http://www.graphviz.org/download/手动构建

步骤2:为Python安装graphviz模块

点:

  • 点安装graphviz

康达:

  • 康达安装graphviz

Step 1: Install Graphviz binary

Windows:

  1. Download Graphviz from http://www.graphviz.org/download/
  2. Add below to PATH environment variable (mention the installed graphviz version):
    • C:\Program Files (x86)\Graphviz2.38\bin
    • C:\Program Files (x86)\Graphviz2.38\bin\dot.exe
  3. Close any opened Juypter notebook and the command prompt
  4. Restart Jupyter / cmd prompt and test

Linux:

  1. sudo apt-get update
  2. sudo apt-get install graphviz
  3. or build it manually from http://www.graphviz.org/download/

Step 2: Install graphviz module for python

pip:

  • pip install graphviz

conda:

  • conda install graphviz

回答 8

尝试conda install graphviz。我有同样的问题,我通过MacOS中提到的命令解决了。

Try conda install graphviz. I had the same problem, I resolved it by mentioned command in MacOS.


回答 9

对我来说,在Windows10上使用conda install graphvizconda install python-graphviz安装GraphViz所需的路径是C:/ ProgramData / Anaconda3 / Library / bin / graphviz /。即添加

import os
os.environ["PATH"] += os.pathsep + 'C:/ProgramData/Anaconda3/Library/bin/graphviz/'

为我解决了这个问题。

Using conda install graphviz and conda install python-graphviz to install GraphViz on Windows10 the path needed was C:/ProgramData/Anaconda3/Library/bin/graphviz/ for me. I.e. adding

import os
os.environ["PATH"] += os.pathsep + 'C:/ProgramData/Anaconda3/Library/bin/graphviz/'

solved the issue for me.


回答 10

conda install python-graphviz

对于Windows,请安装Python Graphviz,它将在路径中包含可执行文件。

conda install python-graphviz

For Windows, install the Python Graphviz which will include the executables in the path.


回答 11

在Ubuntu Linux上,这为我解决了问题:

pip install graphviz
sudo apt-get install graphviz

conda install -c conda-forge graphviz如果使用Anaconda,也可以尝试代替pip。

On Ubuntu Linux this solved it for me:

pip install graphviz
sudo apt-get install graphviz

You could also try conda install -c conda-forge graphviz instead of pip if using Anaconda.


回答 12

在为自己解决此问题时,我使用了此GitHub教程,该教程分析了导致此问题的原因。如果我们在两行之间阅读,它说它需要系统以及python graph viz。除了conda install,我们还需要运行:

conda install -c conda-forge python-graphviz

然后重启内核;它就像一个魅力。

When solving this issue for myself, I used this GitHub tutorial, which analysed the cause of this issue. If we read in between the lines, it says it needs system as well as python graph viz. In addition to conda install, we would need to run:

conda install -c conda-forge python-graphviz

Then restart the kernel; it works like a charm.


回答 13

1)Graphviz –在系统的特定位置下载解压缩文件(pip在Windows中不起作用),并在每个程序中手动设置的路径中包含bin文件夹(“在Windows中设置环境变量”或)

import os
os.environ["PATH"] += os.pathsep + 'C:/GraphViz/bin'

2)然后将模型绘制

clf = xgb.train(params, d_train, 1000, evals=evallist, early_stopping_rounds=10)
xgb.plot_tree(clf)
plt.rcParams['figure.figsize'] = [50, 10]
plt.show()

1) Graphviz – download unzip in a particular place in the system (pip does not work in windows ) and include the bin folder in the path (‘set environment variables in windows’ OR) set manually in each program

import os
os.environ["PATH"] += os.pathsep + 'C:/GraphViz/bin'

2) Then put the model to plot

clf = xgb.train(params, d_train, 1000, evals=evallist, early_stopping_rounds=10)
xgb.plot_tree(clf)
plt.rcParams['figure.figsize'] = [50, 10]
plt.show()

回答 14

安装软件包后(如果尚未安装,请链接),将dot.exe的路径添加为新的系统变量。

默认路径是:

C:\ Program Files(x86)\ Graphviz2.38 \ bin \ dot.exe

在此处输入图片说明

After you’ve installed the package (link if you haven’t), add the path to dot.exe as a new system variable.

Default path is:

C:\Program Files (x86)\Graphviz2.38\bin\dot.exe

enter image description here


回答 15

我在使用Jupyter的Linux上遇到了相同的问题。

为了解决这个问题,我已经将点库添加到python sys.path中

首先:检查是否dot已安装,

然后:
找到他的路径whereis dot-> / local / notebook / miniconda2 / envs / ik2 / bin / dot

最后在python脚本中:sys.path.append(“ / local / notebook / miniconda2 / envs / ik2 / bin / dot”)

I had the same issue on Linux with Jupyter.

To solve it I’ve added the dot library to python sys.path

First: check if dot is installed,

Then:
find his path whereis dot -> /local/notebook/miniconda2/envs/ik2/bin/dot

Finally in python script : sys.path.append(“/local/notebook/miniconda2/envs/ik2/bin/dot”)


回答 16

首先,您应该使用pip install,然后在http://www.graphviz.org/Download_windows.php中下载另一个软件包 ,并将安装位置添加到环境路径中,然后它可以工作。

First, you should use pip install, and then download another package in http://www.graphviz.org/Download_windows.php and add the install location into the environmental path, then it works.


回答 17

在Mac OS(El Capitan)上,我使用PyCharm IDE遇到了相同的错误消息。我已按照RZK的答案中的建议使用brew安装了Graphviz,并使用PyCharm 安装了graphviz python软件包(我可以通过dot -V在终端中尝试并获取以下内容来检查Graphviz是否已正确安装:dot - graphviz version 2.40.1 (20161225.0304))。但是,当尝试从PyCharm调用Graphviz时,我仍然收到错误消息。

我必须按照此问题的答案中的建议,在PyCharm选项中添加路径/ usr / local / bin 。

I had the same error message on Mac OS (El Capitan), using the PyCharm IDE. I had installed Graphviz using brew, as recommended in RZK’s answer, and installed the graphviz python package using PyCharm (I could check Graphviz was installed correctly by trying dot -V in a terminal and getting: dot - graphviz version 2.40.1 (20161225.0304)). Yet I was still getting the error message when trying to call Graphviz from PyCharm.

I had to add the path /usr/local/bin in PyCharm options, as recommended in the answer to this question to resolve the problem.


回答 18

这显示了一些路径问题:

pip install graphviz

所以这对我有用:

sudo apt-get install graphviz

This is showing some path issue:

pip install graphviz

So this worked for me:

sudo apt-get install graphviz

回答 19

我在macOS Catalina 10.15.3上,并且遇到了类似的错误: ExecutableNotFound: failed to execute ['dot', '-Tsvg'], make sure the Graphviz executables are on your systems' PATH

使用以下方法修复了该问题:

pip3 install graphvizbrew install graphviz

请注意,pip3 install只会返回成功消息,Successfully installed graphviz-0.13.2因此我们仍然需要运行brew install以获得graphviz 2.42.3(截至2020年3月10日,下午6点)。

I’m on macOS Catalina 10.15.3, and I had a similar error: ExecutableNotFound: failed to execute ['dot', '-Tsvg'], make sure the Graphviz executables are on your systems' PATH

Fixed it with:

pip3 install graphviz AND brew install graphviz

Note the pip3 install will only return the success message Successfully installed graphviz-0.13.2 so we still need to run brew install to get graphviz 2.42.3 (as of 10 Mar 2020, 6PM).


回答 20

对于没有root权限并因此无法sudo按照其他答案中的建议使用命令的Linux用户…

首先,通过以下方法激活您的conda虚拟环境(如果要使用):

source activate virtual-env-name

然后安装graphviz,即使您已经使用pip完成了它:

conda install graphviz

然后复制以下命令的结果:

whereis dot

就我而言,其输出为:

/home/nader/anaconda2/bin/dot

并将其添加到您的PATH变量中。只需运行以下命令

nano ~/.bashrc

并将这些行添加到打开的文件的末尾:

PATH="/home/username/anaconda2/bin/dot:$PATH"
export PATH

现在按Ctrl+ O,然后Ctrl+ X保存并退出。

现在应该解决问题。

Pycharm用户,请注意:Pycharm并不总是看到与您的终端相同的PATH变量。该解决方案不适用于Pycharm以及其他IDE。但是您可以通过添加以下代码行来解决此问题:

os.environ["PATH"] += os.pathsep + '/home/nader/anaconda2/bin'

到您的python程序。不要忘记

import os

首先:)

编辑:如果您不想使用conda,您仍然可以没有任何root权限的情况下从此处安装graphviz ,并将bin文件夹添加到PATH变量中。我没有测试。

For Linux users who don’t have root access and hence can’t use sudo command as suggested in other answers…

First, activate your conda virtual-environment (if you want to use one) by:

source activate virtual-env-name

Then install graphviz, even if you have already done it using pip:

conda install graphviz

then copy the result of the following command:

whereis dot

In my case, its output is:

/home/nader/anaconda2/bin/dot

and add it to your PATH variable. Just run the command below

nano ~/.bashrc

and add these lines to the end of the opened file:

PATH="/home/username/anaconda2/bin/dot:$PATH"
export PATH

now press Ctrl+O and then Ctrl+X to save and exit.

Problem should be solved by now.

Pycharm users, please note: Pycharm does not always see the PATH variable the same as your terminal. This solution does not work for Pycharm, and maybe other IDEs. But you can fix this by adding this line of code:

os.environ["PATH"] += os.pathsep + '/home/nader/anaconda2/bin'

to your python program. Do not forget to

import os

first :)

Edit: If you don’t want to use conda, you can still install graphviz from here without any root permissions and add the bin folder to your PATH variable. I didn’t test this.


回答 21

1.从以下位置安装Windows软件包:https ://graphviz.gitlab.io/_pages/Download/Download_windows.html 并下载msi文件

添加环境变量2.将C:\ Program Files(x86)\ Graphviz2.38 \ bin添加到用户路径

  1. 将C:\ Program Files(x86)\ Graphviz2.38 \ bin \ dot.exe添加到系统路径

  2. 重新启动您的python笔记本。

会的。

1.install windows package from: https://graphviz.gitlab.io/_pages/Download/Download_windows.html and download msi file

Add in Environmental variables 2. Add C:\Program Files (x86)\Graphviz2.38\bin to User path

  1. Add C:\Program Files (x86)\Graphviz2.38\bin\dot.exe to System Path

  2. Restart your python notebook.

It will work.


回答 22

graphviz添加到系统路径

  1. Windows-编辑系统环境变量。
  2. 选择环境变量。
  3. 选择路径-新建
  4. 添加graphviz的路径

例如:C:\ Users \ AppData \ Local \ Continuum \ anaconda3 \ Library \ bin \ graphviz

Add graphviz to the System Path

  1. Windows – Edit the System Environment Variables.
  2. Choose Environment Variables.
  3. Select Path – New
  4. Add the Path of graphviz

Ex: C:\Users\AppData\Local\Continuum\anaconda3\Library\bin\graphviz


回答 23

OS Mojave 10.14。,Python 3.6

使用pip install graphviz在终端上有很好的反馈,但是当我尝试在Jupyter笔记本中绘制图形时导致使用此错误。然后brew install graphviz,我运行,这在终端中给出了错误。然后我跑conda install graphviz了,图开始工作了。

来自@Leighton的评论:pip仅会遇到与您相同的路径问题,而conda仅会导致导入错误。

OS Mojave 10.14., Python 3.6

Using pip install graphviz had good feedback in terminal, but lead to this error when I tried to make a graph in a Jupyter notebook. I then ran brew install graphviz, which gave an error in terminal. Then I ran conda install graphviz and the graph worked.

From @Leighton’s comment: pip only gets path problem same as yours and conda only gets import error.


回答 24

import os
os.environ["PATH"] += os.pathsep + "/Macintosh HD⁩/anaconda3⁩/lib⁩/⁨python3.7⁩/site-packages⁩/sphinx⁩/templates⁩/graphviz"

这为我解决了MAC上的PATH问题!

import os
os.environ["PATH"] += os.pathsep + "/Macintosh HD⁩/anaconda3⁩/lib⁩/⁨python3.7⁩/site-packages⁩/sphinx⁩/templates⁩/graphviz"

This solved the PATH issue on MAC for me!


回答 25

如果您不是使用Conda而是使用Vanilla Python,则“ brew install graphviz”有效。

If you are not using Conda but vanilla Python, ‘brew install graphviz’ works.


回答 26

#Write this on anaconda prompt in admin mode
conda install -c anaconda graphviz
conda install -c conda-forge python-graphviz
conda install -c conda-forge/label/broken python-graphviz
conda install -c conda-forge/label/cf201901 python-graphviz
conda install -c conda-forge/label/cf202003 python-graphviz

#check dot -v in window's cmd prompt
C:\WINDOWS\system32>dot -V
dot - graphviz version 2.38.0 (20140413.2041)
(this means graphviz installed successfully)

#Add path to sys and user eve variables
PATH
C:\Anaconda3\pkgs\graphviz-2.38-hfd603c8_2\Library\bin
(search bin folder of graphviz and then copy n paste path in env variables)

#Re-run all cmds in jyupter notebook
#if error occurs (less chances)
#then 
#Restart anaconda and again run all cmds in jyupter notebook
eg.
import graphviz as gp
with open("tree.dot") as f:
    dot_read=f.read()
display(gp.Source(dot_read))
#Write this on anaconda prompt in admin mode
conda install -c anaconda graphviz
conda install -c conda-forge python-graphviz
conda install -c conda-forge/label/broken python-graphviz
conda install -c conda-forge/label/cf201901 python-graphviz
conda install -c conda-forge/label/cf202003 python-graphviz

#check dot -v in window's cmd prompt
C:\WINDOWS\system32>dot -V
dot - graphviz version 2.38.0 (20140413.2041)
(this means graphviz installed successfully)

#Add path to sys and user eve variables
PATH
C:\Anaconda3\pkgs\graphviz-2.38-hfd603c8_2\Library\bin
(search bin folder of graphviz and then copy n paste path in env variables)

#Re-run all cmds in jyupter notebook
#if error occurs (less chances)
#then 
#Restart anaconda and again run all cmds in jyupter notebook
eg.
import graphviz as gp
with open("tree.dot") as f:
    dot_read=f.read()
display(gp.Source(dot_read))

回答 27

尝试在anaconda提示中一一键入以下代码。

这对我有用。

资料来源:https : //anaconda.org/conda-forge/python-graphviz

conda install -c conda-forge python-graphviz
conda install -c conda-forge/label/broken python-graphviz
conda install -c conda-forge/label/cf201901 python-graphviz
conda install -c conda-forge/label/cf202003 python-graphviz 

try typing the following code in anaconda prompt one by one.

this worked for me.

Source: https://anaconda.org/conda-forge/python-graphviz

conda install -c conda-forge python-graphviz
conda install -c conda-forge/label/broken python-graphviz
conda install -c conda-forge/label/cf201901 python-graphviz
conda install -c conda-forge/label/cf202003 python-graphviz 

回答 28

尝试在python import sys中做到这一点!conda install –yes –prefix {sys.prefix} graphviz import graphviz

trying doing this in python import sys !conda install –yes –prefix {sys.prefix} graphviz import graphviz


如何更新Python?

问题:如何更新Python?

我从2012年初开始安装了2.7版。对于在安装最新版本之前是否应该完全卸载并擦除此版本,我无法达成共识。

“软”删除旧版本?硬删除/清除旧版本?安装在顶部?

我在某处看到了一个特殊的安装/升级过程,该过程使用Python安装的“分段”方法,将不同的版本分开并保持功能。不知道这是否是事实上的标准方法。

我还想知道Revo是否太过热情,是否可能导致清除仍然需要的残留物(例如环境/ PATH变量)而引起问题。

(Win7 x64,32位Python)

I have version 2.7 installed from early 2012. I can’t find any consensus on whether I should completely uninstall and wipe this version before putting on the latest version.

“Soft”-removing old versions? Hard-removing/wiping old versions? Installing over top?

I’ve seen somewhere a special install/upgrade process using a “segmenting” method of Python installations, keeping different versions separate and apart, but functional. Not sure if this is the standard, de facto way.

I also wonder if Revo gets too overzealous and may cause issues with wiping out still-needed remnants, like environment/PATH variables.

(Win7 x64, 32-bit Python)


回答 0

更新日期:2018-07-06

这个帖子现在已经快5年了!2020年,Python-2.7将停止从python.org接收官方更新。此外,还发布了Python-3.7。查看Python-Future,了解如何使您的Python-2代码与Python-3兼容。为了更新conda,文档现在建议conda update --all在您的每个conda环境中使用更新该版本的所有软件包和Python可执行文件。另外,由于它们将名称更改为Anaconda,所以我不知道Windows注册表项是否仍然相同。

更新日期:2017-03-24

自2015年6月以来,没有对Python(x,y)进行任何更新,因此我认为可以断定它已被放弃。

更新:2016-11-11

正如下面的@cxw注释所示,这些答案适用于相同的位版本,按位版本,我的意思是64位与32位。例如,这些答案将适用于从64位Python-2.7.10更新到64位Python-2.7.11,相同的位版本。虽然可以将两个不同的Python版本一起安装,但这需要一些技巧,因此我将为读者保存该练习。如果您不想黑客,我建议如果切换位版本,请先删除其他位版本。

更新日期:2016-05-16
  • 通过禁用更改Windows 和注册表的选项,AnacondaMiniConda可以与现有的Python安装一起使用PATH。解压后,conda在您的binPyPI中创建符号链接到或安装conda。然后创建另一个名为符号链接conda-activateactivate在巨蟒/ Miniconda根bin文件夹。现在,Anaconda / Miniconda就像Ruby RVM。仅用于conda-activate root启用Anaconda / Miniconda。
  • 便携式Python已不再开发或维护。

TL; DR

  • 使用Anaconda或miniconda,然后执行conda update --all以保持每个conda环境的更新,
  • 同样重要的版本官方的Python比如 2.7.5),只需安装过旧的( 2.7.4),
  • 官方Python的不同主要版本 3.3),与老,设置路径/联装并排方点到显性的( 2.7),快捷方式等(在bash $ ln /c/Python33/python.exe python3)。

答案取决于:

  1. 如果OP具有2.7.x,并且要安装较新的2.7.x,则

    • 如果使用MSI安装程序Python官方网站上,只要安装了旧版本,安装程序会发出警告,它会删除并替换旧版本; 前后检查“控制面板”中的“已安装程序”,以确认旧版本已被新版本替换;2.7.x的较新版本向后兼容,因此这是完全安全的,因此,IMHO 2.7.x的多个版本永远不需要。
    • 如果是从源代码构建的,那么您可能应该构建在一个全新的,干净的目录中,然后在通过所有测试并且确信它已成功构建后,将路径指向新的构建,但是您可能希望保留旧的进行构建,因为从源构建可能偶尔会遇到问题。请参阅我的指南,以在带有SDK 7.0的Windows 7上构建Python x64
    • 如果从诸如Python(x,y)之类的发行版进行安装,请访问其网站。Python(x,y)已被放弃。 我相信可以使用其包管理器在Python(x,y)内处理更新,但是更新更新也包含在其网站上。我找不到具体的参考,所以也许有人可以对此发表意见。与ActiveState相似,并且可能是有思想的,Python(x,y)明确指出它与Python的其他安装不兼容:

      建议在安装Python(x,y)之前先卸载所有其他Python发行版

    • Enthought Canopy使用MSI,并将分别安装到所有用户中或为所有用户安装,Program Files\Enthoughthome\AppData\Local\Enthought\Canopy\App针对每个用户安装。通过使用内置的更新工具来更新较新的安装。查看他们的文档
    • ActiveState还使用MSI,因此可以在较旧的安装之上安装较新的安装。查看其安装说明

      其他Python 2.7安装在Windows上,ActivePython 2.7无法与其他Python 2.7安装共存(例如,来自python.org的Python 2.7构建)。在安装ActivePython 2.7之前,请卸载其他所有Python 2.7安装。

    • Sage建议您将其安装到虚拟机中,并提供可用于此目的的Oracle VirtualBox映像文件。发出sage -upgrade命令在内部处理升级。
    • 可以使用以下conda命令更新Anaconda

      conda update --all

      Anaconda / Miniconda允许用户创建环境来管理多个Python版本,包括Python- 2.6、2.7、3.3、3.4 和3.5。Anaconda / Miniconda的根安装当前基于Python-2.7或Python-3.5。

      Anaconda可能会破坏其他Python安装。安装使用MSI安装程序。 [ 更新:2016-05-16] Anaconda和Miniconda现在使用.exe安装程序,并提供选项来禁用Windows PATH和注册表更改。

      因此,根据安装方式和安装过程中选择的选项,可以在不中断现有Python安装的情况下安装Anaconda / Miniconda。如果.exe使用安装程序和选项来改变的Windows PATH和注册表都没有禁用,则任何以前的Python的安装将被禁用,但只需卸载Python/ Miniconda安装应恢复原来的Python安装,也许除了Windows注册表Python\PythonCore键。

      Python/ Miniconda使得下面的注册表编辑无论安装选项:HKCU\Software\Python\ContinuumAnalytics\使用下列按键:HelpInstallPathModulesPythonPath– Python官方注册过这些按键,但下Python\PythonCore。还为Anaconda \ Miniconda注册了卸载信息。除非在安装过程中选择“在Windows中注册”选项,否则它不会创建PythonCore,因此像Visual Studio的Python Tools这样的集成不会自动看到Anaconda / Miniconda。如果注册Python/ Miniconda选项激活,那么我认为您现有的Python Windows注册表项将被改变和卸载可能不会恢复它们。

    • 我认为,可以通过WinPython控制面板处理WinPython更新。
    • PortablePython不再被开发它没有更新方法。可能更新可以解压缩到一个新的目录,然后App\lib\site-packagesApp\Scripts可以复制到新安装的,但如果没有工作,然后重新安装所有的包可能是必要的。使用pip list查看包安装了什么,它们的版本。有些是由PortablePython安装的。使用easy_install pip如果未安装它安装点子。
  2. 如果OP具有2.7.x,并且想要安装其他版本,例如 <= 2.6.x或> = 3.xx,则可以并排安装不同版本。您必须选择要与*.py文件关联的Python版本(如果有),以及要在路径中使用的版本,尽管如果使用BASH则应该能够设置具有不同路径的shell 。AFAIK 2.7.x向后兼容2.6.x,因此不需要IMHO并排安装,但是Python-3.xx不向后兼容,因此我的建议是将Python-2.7放在您的路径上并具有通过创建指向可执行文件的快捷方式python3(这是Linux上的常见设置),可以将python-3作为可选版本。Windows上官方的Python默认安装路径是

    • 适用于3.3.x的C:\ Python33(最新2013-07-29)
    • C:\ Python32 for 3.2.x
    • &C。
    • C:\ Python27 for 2.7.x(最新2013-07-29)
    • C:\ Python26 for 2.6.x
    • &C。
  3. 如果OP不是在更新Python,而只是在更新软件包,则他们可能希望研究virtualenv,以使特定于其开发项目的软件包的不同版本分开。Pip还是更新软件包的好工具。如果软件包使用二进制安装程序,则通常在安装新软件包之前先卸载旧软件包。

我希望这可以消除任何混乱。

UPDATE: 2018-07-06

This post is now nearly 5 years old! Python-2.7 will stop receiving official updates from python.org in 2020. Also, Python-3.7 has been released. Check out Python-Future on how to make your Python-2 code compatible with Python-3. For updating conda, the documentation now recommends using conda update --all in each of your conda environments to update all packages and the Python executable for that version. Also, since they changed their name to Anaconda, I don’t know if the Windows registry keys are still the same.

UPDATE: 2017-03-24

There have been no updates to Python(x,y) since June of 2015, so I think it’s safe to assume it has been abandoned.

UPDATE: 2016-11-11

As @cxw comments below, these answers are for the same bit-versions, and by bit-version I mean 64-bit vs. 32-bit. For example, these answers would apply to updating from 64-bit Python-2.7.10 to 64-bit Python-2.7.11, ie: the same bit-version. While it is possible to install two different bit versions of Python together, it would require some hacking, so I’ll save that exercise for the reader. If you don’t want to hack, I suggest that if switching bit-versions, remove the other bit-version first.

UPDATES: 2016-05-16
  • Anaconda and MiniConda can be used with an existing Python installation by disabling the options to alter the Windows PATH and Registry. After extraction, create a symlink to conda in your bin or install conda from PyPI. Then create another symlink called conda-activate to activate in the Anaconda/Miniconda root bin folder. Now Anaconda/Miniconda is just like Ruby RVM. Just use conda-activate root to enable Anaconda/Miniconda.
  • Portable Python is no longer being developed or maintained.

TL;DR

  • Using Anaconda or miniconda, then just execute conda update --all to keep each conda environment updated,
  • same major version of official Python (e.g. 2.7.5), just install over old (e.g. 2.7.4),
  • different major version of official Python (e.g. 3.3), install side-by-side with old, set paths/associations to point to dominant (e.g. 2.7), shortcut to other (e.g. in BASH $ ln /c/Python33/python.exe python3).

The answer depends:

  1. If OP has 2.7.x and wants to install newer version of 2.7.x, then

    • if using MSI installer from the official Python website, just install over old version, installer will issue warning that it will remove and replace the older version; looking in “installed programs” in “control panel” before and after confirms that the old version has been replaced by the new version; newer versions of 2.7.x are backwards compatible so this is completely safe and therefore IMHO multiple versions of 2.7.x should never necessary.
    • if building from source, then you should probably build in a fresh, clean directory, and then point your path to the new build once it passes all tests and you are confident that it has been built successfully, but you may wish to keep the old build around because building from source may occasionally have issues. See my guide for building Python x64 on Windows 7 with SDK 7.0.
    • if installing from a distribution such as Python(x,y), see their website. Python(x,y) has been abandoned. I believe that updates can be handled from within Python(x,y) with their package manager, but updates are also included on their website. I could not find a specific reference so perhaps someone else can speak to this. Similar to ActiveState and probably Enthought, Python (x,y) clearly states it is incompatible with other installations of Python:

      It is recommended to uninstall any other Python distribution before installing Python(x,y)

    • Enthought Canopy uses an MSI and will install either into Program Files\Enthought or home\AppData\Local\Enthought\Canopy\App for all users or per user respectively. Newer installations are updated by using the built in update tool. See their documentation.
    • ActiveState also uses an MSI so newer installations can be installed on top of older ones. See their installation notes.

      Other Python 2.7 Installations On Windows, ActivePython 2.7 cannot coexist with other Python 2.7 installations (for example, a Python 2.7 build from python.org). Uninstall any other Python 2.7 installations before installing ActivePython 2.7.

    • Sage recommends that you install it into a virtual machine, and provides a Oracle VirtualBox image file that can be used for this purpose. Upgrades are handled internally by issuing the sage -upgrade command.
    • Anaconda can be updated by using the conda command:

      conda update --all
      

      Anaconda/Miniconda lets users create environments to manage multiple Python versions including Python-2.6, 2.7, 3.3, 3.4 and 3.5. The root Anaconda/Miniconda installations are currently based on either Python-2.7 or Python-3.5.

      Anaconda will likely disrupt any other Python installations. Installation uses MSI installer. [UPDATE: 2016-05-16] Anaconda and Miniconda now use .exe installers and provide options to disable Windows PATH and Registry alterations.

      Therefore Anaconda/Miniconda can be installed without disrupting existing Python installations depending on how it was installed and the options that were selected during installation. If the .exe installer is used and the options to alter Windows PATH and Registry are not disabled, then any previous Python installations will be disabled, but simply uninstalling the Anaconda/Miniconda installation should restore the original Python installation, except maybe the Windows Registry Python\PythonCore keys.

      Anaconda/Miniconda makes the following registry edits regardless of the installation options: HKCU\Software\Python\ContinuumAnalytics\ with the following keys: Help, InstallPath, Modules and PythonPath – official Python registers these keys too, but under Python\PythonCore. Also uninstallation info is registered for Anaconda\Miniconda. Unless you select the “Register with Windows” option during installation, it doesn’t create PythonCore, so integrations like Python Tools for Visual Studio do not automatically see Anaconda/Miniconda. If the option to register Anaconda/Miniconda is enabled, then I think your existing Python Windows Registry keys will be altered and uninstallation will probably not restore them.

    • WinPython updates, I think, can be handled through the WinPython Control Panel.
    • PortablePython is no longer being developed. It had no update method. Possibly updates could be unzipped into a fresh directory and then App\lib\site-packages and App\Scripts could be copied to the new installation, but if this didn’t work then reinstalling all packages might have been necessary. Use pip list to see what packages were installed and their versions. Some were installed by PortablePython. Use easy_install pip to install pip if it wasn’t installed.
  2. If OP has 2.7.x and wants to install a different version, e.g. <=2.6.x or >=3.x.x, then installing different versions side-by-side is fine. You must choose which version of Python (if any) to associate with *.py files and which you want on your path, although you should be able to set up shells with different paths if you use BASH. AFAIK 2.7.x is backwards compatible with 2.6.x, so IMHO side-by-side installs is not necessary, however Python-3.x.x is not backwards compatible, so my recommendation would be to put Python-2.7 on your path and have Python-3 be an optional version by creating a shortcut to its executable called python3 (this is a common setup on Linux). The official Python default install path on Windows is

    • C:\Python33 for 3.3.x (latest 2013-07-29)
    • C:\Python32 for 3.2.x
    • &c.
    • C:\Python27 for 2.7.x (latest 2013-07-29)
    • C:\Python26 for 2.6.x
    • &c.
  3. If OP is not updating Python, but merely updating packages, they may wish to look into virtualenv to keep the different versions of packages specific to their development projects separate. Pip is also a great tool to update packages. If packages use binary installers I usually uninstall the old package before installing the new one.

I hope this clears up any confusion.


回答 1

最好的解决方案是在多个路径中安装不同的Python版本。

例如。C:\ Python27(适用于2.7)和C:\ Python33(适用于3.3)。

阅读以获取更多信息:如何在Windows上运行多个Python版本

The best solution is to install the different Python versions in multiple paths.

eg. C:\Python27 for 2.7, and C:\Python33 for 3.3.

Read this for more info: How to run multiple Python versions on Windows


回答 2

  • 官方Python .msi安装程序旨在替代:

    • 以前的任何微型发行版(在xyz中z为“微型”),因为可以保证它们是向后兼容和二进制兼容的
    • 任何微型版本的“快照”(从源构建)安装
  • 快照安装程序旨在用较低的微型版本替换任何快照。

(见的2.X负责代码为3.X

任何其他版本不一定兼容,因此与现有版本一起安装。如果您希望卸载旧版本,则需要手动进行。并卸载您拥有的所有第三方模块:

  • 如果您从bdist_wininst软件包(Windows .exe)安装了任何模块,请在卸载版本之前先将其卸载,否则如果卸载程序具有自定义逻辑,则卸载程序可能无法正常工作
  • 安装了模块 setuptools /的pip驻留在其中,Lib\site-packages之后可以删除
  • 您为每个用户安装的软件包(如果有)驻留在该软件包中,%APPDATA%/Python/PythonXY/site-packages并且同样可以删除
  • Official Python .msi installers are designed to replace:

    • any previous micro release (in x.y.z, z is “micro”) because they are guaranteed to be backward-compatible and binary-compatible
    • a “snapshot” (built from source) installation with any micro version
  • A snapshot installer is designed to replace any snapshot with a lower micro version.

(See responsible code for 2.x, for 3.x)

Any other versions are not necessarily compatible and are thus installed alongside the existing one. If you wish to uninstall the old version, you’ll need to do that manually. And also uninstall any 3rd-party modules you had for it:

  • If you installed any modules from bdist_wininst packages (Windows .exes), uninstall them before uninstalling the version, or the uninstaller might not work correctly if it has custom logic
  • modules installed with setuptools/pip that reside in Lib\site-packages can just be deleted afterwards
  • packages that you installed per-user, if any, reside in %APPDATA%/Python/PythonXY/site-packages and can likewise be deleted

回答 3

我一直只是将新版本安装在最上面,从来没有任何问题。但是,请确保您的路径已更新为指向新版本。

I have always just installed the new version on top and never had any issues. Do make sure that your path is updated to point to the new version though.


scipy.misc模块没有属性读取?

问题:scipy.misc模块没有属性读取?

我正在尝试读取图像。但是,它不接受该scipy.misc.imread零件。这可能是什么原因?

>>> import scipy
>>> scipy.misc
<module 'scipy.misc' from 'C:\Python27\lib\site-packages\scipy\misc\__init__.pyc'>
>>> scipy.misc.imread('test.tif')
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    scipy.misc.imread('test.tif')
AttributeError: 'module' object has no attribute 'imread'

I am trying to read an image with scipy. However it does not accept the scipy.misc.imread part. What could be the cause of this?

>>> import scipy
>>> scipy.misc
<module 'scipy.misc' from 'C:\Python27\lib\site-packages\scipy\misc\__init__.pyc'>
>>> scipy.misc.imread('test.tif')
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    scipy.misc.imread('test.tif')
AttributeError: 'module' object has no attribute 'imread'

回答 0

您需要安装Pillow(以前称为PIL)。从在文档scipy.misc

请注意,Pillow不是SciPy的依赖项,但是如果没有它,下面列表中指示的图像处理功能将不可用:

imread

安装Pillow后,我可以imread如下访问:

In [1]: import scipy.misc

In [2]: scipy.misc.imread
Out[2]: <function scipy.misc.pilutil.imread>

You need to install Pillow (formerly PIL). From the docs on scipy.misc:

Note that Pillow is not a dependency of SciPy but the image manipulation functions indicated in the list below are not available without it:

imread

After installing Pillow, I was able to access imread as follows:

In [1]: import scipy.misc

In [2]: scipy.misc.imread
Out[2]: <function scipy.misc.pilutil.imread>

回答 1

imread在SciPy 1.0.0中已弃用,在1.2.0中将被删除。使用imageio.imread代替。

import imageio
im = imageio.imread('astronaut.png')
im.shape  # im is a numpy array
(512, 512, 3)
imageio.imwrite('imageio:astronaut-gray.jpg', im[:, :, 0])

imread is deprecated in SciPy 1.0.0, and will be removed in 1.2.0. Use imageio.imread instead.

import imageio
im = imageio.imread('astronaut.png')
im.shape  # im is a numpy array
(512, 512, 3)
imageio.imwrite('imageio:astronaut-gray.jpg', im[:, :, 0])

回答 2

版本1.2.0之后,imread贬值!因此,要解决此问题,我必须安装版本1.1.0。

pip install scipy==1.1.0

imread is depreciated after version 1.2.0! So to solve this issue I had to install version 1.1.0.

pip install scipy==1.1.0

回答 3

对于Python 3,最好是使用imreadmatplotlib.pyplot

from matplotlib.pyplot import imread

For Python 3, it is best to use imread in matplotlib.pyplot:

from matplotlib.pyplot import imread

回答 4

如果有人遇到相同的问题,请卸载scipy并安装scipy == 1.1.0

$ pip uninstall scipy

$ pip install scipy==1.1.0

In case anyone encountering the same issue, please uninstall scipy and install scipy==1.1.0

$ pip uninstall scipy

$ pip install scipy==1.1.0

回答 5

您需要Python Imaging Library(PIL),但是but!PIL项目似乎已被放弃。特别是,它尚未移植到Python3。因此,如果要在Python 3中使用PIL功能,则最好使用Pillow,它是PIL的半官方分支,并且正在积极开发中。实际上,如果您完全需要现代的PIL实现,我建议您选择Pillow。就像一样简单pip install pillow。由于它使用与PIL相同的命名空间,因此实质上是直接替代。

这个叉子有多“半官方”?你可能会问。“ 枕头”文档的“ 关于”页面说:

自上次发布PIL之后,随着时间的流逝,新发布PIL的可能性降低。但是,我们尚未听到官方的“ PIL已死”声明。因此,如果您仍然希望支持PIL,请先在此处报告问题,然后在此处打开相应的枕头票。

请提供第一张票证的链接,以便我们可以跟踪上游问题。

但是,PIL 官方站点上的最新PIL版本发布于2009年11月15日。我认为,在将近八年没有新版本发布之时,我们可以肯定地说Pillow是PIL的继承者。因此,即使您不需要Python 3支持,我也建议您避免使用PyPI中可用的古老PIL 1.1.6发行版,而只需安装新的,最新的,兼容的Pillow。

You need the Python Imaging Library (PIL) but alas! the PIL project seems to have been abandoned. In particular, it hasn’t been ported to Python 3. So if you want PIL functionality in Python 3, you’ll do well do use Pillow, which is the semi-official fork of PIL and appears to be actively developed. Actually, if you need a modern PIL implementation at all I’d recommend Pillow. It’s as simple as pip install pillow. As it uses the same namespace as PIL it’s essentially a drop-in replacement.

How “semi-official” is this fork? you may ask. The About page of the Pillow docs say this:

As more time passes since the last PIL release, the likelihood of a new PIL release decreases. However, we’ve yet to hear an official “PIL is dead” announcement. So if you still want to support PIL, please report issues here first, then open corresponding Pillow tickets here.

Please provide a link to the first ticket so we can track the issue(s) upstream.

However, the most recent PIL release on the official PIL site is dated November 15, 2009. I think we can safely proclaim Pillow as the successor of PIL after (as of this writing) nearly eight years of no new releases. So even if you don’t need Python 3 support, I suggest you eschew the ancient PIL 1.1.6 distribution available in PyPI and just install fresh, up-to-date, compatible Pillow.


回答 6

通过以下命令安装枕头库:

pip install pillow

请注意,所选答案已过时。查看SciPy的文档

请注意,Pillow(https://python-pillow.org/)不是SciPy的依赖项,但如果没有它,则下面列表中指示的图像处理功能将不可用。

Install the Pillow library by following commands:

pip install pillow

Note, the selected answer has been outdated. See the docs of SciPy

Note that Pillow (https://python-pillow.org/) is not a dependency of SciPy, but the image manipulation functions indicated in the list below are not available without it.


回答 7

答案是:misc.imread在SciPy 1.0.0中已弃用,在1.2.0中将被删除。imageio是一个选项,它将返回类型为object的对象:

<class 'imageio.core.util.Image'>

但要使用image2,而不要使用imageio

import cv2
im = cv2.imread('astronaut.png')

我将是类型: <class 'numpy.ndarray'>

由于numpy数组的计算速度更快。

As answered misc.imread is deprecated in SciPy 1.0.0, and will be removed in 1.2.0. imageio is one option,it will return object of type :

<class 'imageio.core.util.Image'>

but instead of imageio, use cv2

import cv2
im = cv2.imread('astronaut.png')

im will be of type : <class 'numpy.ndarray'>

As numpy arrays are faster to compute.


回答 8

Imread使用PIL库,如果已安装该库,则使用:“ from scipy.ndimage import imread”

资料来源:http : //docs.scipy.org/doc/scipy-0.17.0/reference/generated/scipy.ndimage.imread.html

Imread uses PIL library, if the library is installed use : “from scipy.ndimage import imread”

Source: http://docs.scipy.org/doc/scipy-0.17.0/reference/generated/scipy.ndimage.imread.html


回答 9

python -m pip install pillow

这对我有用。

python -m pip install pillow

This worked for me.


回答 10

您需要一个python图像库(PIL),但是现在仅PIL还不够,您最好安装Pillow。这很好。

You need a python image library (PIL), but now PIL only is not enough, you’d better install Pillow. This works well.


回答 11

在Jupyter Notebook中运行以下命令,我收到了类似的错误消息:

from skimage import data
photo_data = misc.imread('C:/Users/ers.jpg')
type(photo_data)

“错误”消息:

D:\ Program Files(x86)\ Microsoft Visual Studio \ Shared \ Anaconda3_64 \ lib \ site-packages \ ipykernel_launcher.py:3:DeprecationWarning:已imread弃用!imread在SciPy 1.0.0中已弃用,在1.2.0中将被删除。使用imageio.imread 代替。这与ipykernel软件包分开,因此我们可以避免导入,直到

并使用以下我解决了:

import matplotlib.pyplot
photo_data = matplotlib.pyplot.imread('C:/Users/ers.jpg')
type(photo_data)

Running the following in a Jupyter Notebook, I had a similar error message:

from skimage import data
photo_data = misc.imread('C:/Users/ers.jpg')
type(photo_data)

‘error’ msg:

D:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\ipykernel_launcher.py:3: DeprecationWarning: imread is deprecated! imread is deprecated in SciPy 1.0.0, and will be removed in 1.2.0. Use imageio.imread instead. This is separate from the ipykernel package so we can avoid doing imports until

And using the following I got it solved:

import matplotlib.pyplot
photo_data = matplotlib.pyplot.imread('C:/Users/ers.jpg')
type(photo_data)

回答 12

我在jupyter笔记本上具有图像提取所需的所有软件包,但即使如此,它仍然显示相同的错误。

Jupyter Notebook上的错误

阅读以上评论,我已经安装了必需的软件包。请告诉我是否错过了一些包裹。

pip3 freeze | grep -i -E "pillow|scipy|scikit-image"
Pillow==5.4.1
scikit-image==0.14.2

scipy==1.2.1

I have all the packages required for the image extraction on jupyter notebook, but even then it shows me the same error.

Error on Jupyter Notebook

Reading the above comments, I have installed the required packages. Please do tell if I have missed some packages.

pip3 freeze | grep -i -E "pillow|scipy|scikit-image"
Pillow==5.4.1
scikit-image==0.14.2

scipy==1.2.1

回答 13

在python 3.6中为我工作的解决方案如下

py -m pip安装枕头

The solution that work for me in python 3.6 is the following

py -m pip install Pillow


将–user和–prefix错误与setup.py install结合使用

问题:将–user和–prefix错误与setup.py install结合使用

我试图将Python软件包安装到最近可以访问的系统中。我试图利用Python相对较新的每用户site-packages目录以及new选项--user。(该选项当前未公开,但是适用于Python 2.6+;您可以通过运行来查看帮助python setup.py install --help。)

当我尝试跑步

python setup.py install --user

在我下载的任何软件包上,总是出现以下错误:

error: can't combine user with with prefix/exec_prefix/home or install_(plat)base

错误是非常令人费解,因为你可以看到,我不提供--prefix--exec-prefix--install-base,或--install-platbase标志作为命令行选项。我浪费了很多时间试图找出问题所在。我在下面记录我的答案,以期使其他一些可怜的人免于数小时的

I was trying to install Python packages a system I recently gained access to. I was trying to take advantage of Python’s relatively new per user site-packages directory, and the new option --user. (The option is currently undocumented, however it exists for Python 2.6+; you can see the help by running python setup.py install --help.)

When I tried running

python setup.py install --user

on any package I downloaded, I always got the following error:

error: can't combine user with with prefix/exec_prefix/home or install_(plat)base

The error was extremely perplexing because, as you can see, I wasn’t providing the --prefix, --exec-prefix, --install-base, or --install-platbase flags as command line options. I wasted a lot of time trying to figure out what the problem was. I document my answer below, in hopes to spare some other poor soul a few hours of yak shaving.


回答 0

一种解决方法:

pip install --user --install-option="--prefix=" <package_name>

要么

python setup.py install --user --prefix=

请注意,后面没有文本(甚至没有空格)=

千万不能忘记的--user标志。

安装多个软件包:

~/.pydistutils.cfg使用以下内容创建(或等效于您的操作系统/平台):

[install]
prefix=

请注意,后面没有文本(甚至没有空格)=

然后运行必要pip install --userpython setup.py install --user命令。千万不能忘记的--user标志。

最后,删除或重命名此文件。如果--user以此用户身份在系统范围内安装Python软件包(即,不带),则将该文件保留为当前内容将导致问题~/.pydistutils.cfg

此问题的原因

这似乎与OpenSUSE和RedHat都存在问题,导致这些平台上的virtualenv出现错误

该错误源于系统级distutils配置文件(在我的情况下/usr/lib64/python2.6/distutils/distutils.cfg

[install]
prefix=/usr/local

基本上,这等效于始终以方式运行install命令install --prefix=/usr/local。您必须使用上面的一种技术来覆盖此规范。

One time workaround:

pip install --user --install-option="--prefix=" <package_name>

or

python setup.py install --user --prefix=

Note that there is no text (not even whitespace) after the =.

Do not forget the --user flag.

Installing multiple packages:

Create ~/.pydistutils.cfg (or equivalent for your OS/platform) with the following contents:

[install]
prefix=

Note that there is no text (not even whitespace) after the =.

Then run the necessary pip install --user or python setup.py install --user commands. Do not forget the --user flag.

Finally, remove or rename this file. Leaving this file present will cause issues when installing Python packages system-wide (i.e., without --user) as this user with this ~/.pydistutils.cfg.

The cause of this issue

This appears to be an issue with both OpenSUSE and RedHat, which has lead to a bug in virtualenv on these platforms.

The error stems from a system-level distutils configuration file (in my case /usr/lib64/python2.6/distutils/distutils.cfg) where there was this

[install]
prefix=/usr/local

Basically, this is equivalent to always running the install command as install --prefix=/usr/local. You have to override this specification using one of the techniques above.


回答 1

正如评论中所指出的那样,公认的答案(@gotgenes,大概拥有基因)可能导致意外的后果。

@rogeleaderr说:“请注意,将文件保存为这样会使Python认为/是您的python库的根目录,如果尝试安装其他新软件包,则会导致令人困惑的问题。”

与其按照@gotgenes的建议写一个新的配置文件,一个更好的选择是--prefix=命令行上添加(等号右边没有文本)作为选项,如

$ python setup.py install --user --prefix=

As has been noted in the comments, the accepted answer (by @gotgenes, who, presumably, has genes) can lead to unexpected consequences.

@rogeleaderr says, “Note that keeping this file like this will make Python think that / is your root python library directory, leading to confusing issues if you try to install other new packages.”

Rather than write a new config file, as @gotgenes recommends, a better option is to add --prefix= (with no text to the right of the equals sign) as an option on the command line, as in

$ python setup.py install --user --prefix=

回答 2

发布信息以节省其他人的时间,因为没有可用的答案对我有用。

在某些环境中,使用--target-t)开关仍然会遇到相同的错误。在对两种Linux版本的测试中,使用--prefix=参数时遇到了相同的问题。

码:

PYTHONUSERBASE=/tmp/ pip install --user --force-reinstall $PACKAGE

说明:我的变通办法似乎可以在许多环境(MacOS,Amazon Linux,Debian)中使用,是将PYTHONUSERBASE环境变量设置为临时位置。 --force-reinstall用于触发本地安装,即使已安装软件包也是如此。

这将导致模块被编译/安装(取决于操作系统和Python版本)以: /tmp/lib/python2.7/site-packages/*

Posting to save others time, as no available answers worked for me…

In some environments, using the --target (-t) switch will still hit the same error. In my testing on two flavors of linux, I encountered the same issue when using the --prefix= parameter.

Code:

PYTHONUSERBASE=/tmp/ pip install --user --force-reinstall $PACKAGE

Explanation: My workaround, which seems to work across many environments (MacOS, Amazon Linux, Debian) is to set the PYTHONUSERBASE environment variable to a temp location. --force-reinstall is used to trigger the local installation even when the package is already installed.

This will result in the module being compiled/installed (depending on the OS and Python version) to: /tmp/lib/python2.7/site-packages/*


回答 3

您可以简单地运行pip install --user .,不需要前缀args。

这是更好的呢,因为如果你的点子被配置为使用Python 3,将默认为python3(我忘了进入python3 setup.py和它2.7下安装了3只包)

(信贷https://stackoverflow.com/a/1550235/4364036

You can simply run pip install --user . , no prefix args required.

This is better anyway because it will default to python3 if your pip is configured to use Python 3. (I forgot to enter python3 setup.py and it installed a 3-only package under 2.7)

(credit https://stackoverflow.com/a/1550235/4364036)


回答 4

我有同样的问题。它隐藏在~/.config/pip/pip.confwith中:

[global]
target=/foo/bar

这种配置是由第三方脚本在不知情的情况下创建的。

我建议检查pip配置文件并删除target=/foo/bar选项。

I had have the same problem. It was hidden inside the ~/.config/pip/pip.conf with:

[global]
target=/foo/bar

Such a config was created by a third-party script without my knowledge.

I suggest checking the pip configuration files and removing the target=/foo/bar options.


ImportError:Windows上没有模块命名的站点

问题:ImportError:Windows上没有模块命名的站点

我正在尝试首次安装Python。我从Python网站下载了以下安装程序: Python 2.7.1 Windows Installer(Windows二进制文件-不包括源代码)。然后,我运行安装程序,选择“所有用户”,一切都很好。我将Python安装到默认位置:

C:\Python27

接下来,要测试Python是否已正确安装,我导航到我的Python目录,并在Windows cmd提示符下运行了“ python”命令。它返回以下错误:

ImportError:没有名为站点的模块

当我执行“ python -v”时,我得到以下信息:

#installing zipimport hook
import zipimport # builtin

#ImportError: No module named site #installed zipimport钩子#clear 内置 ._
#clear sys.path #clear sys.argv
#clear sys.ps1 #clear sys.ps2
#clear sys.exitfunc #clear sys.exc_type
#clear sys.exc_value #clear sys.exc_traceback
#clear sys.last_type #clear sys.last_value
#clear sys.last_traceback #clear sys.path_hooks
#clear sys.path_importer_cache #clear sys.meta_path
#clear sys.flags #clear sys.float_info
#restore sys.stdin #恢复sys.stdout
#restore sys.stderr #cleanup
#cleanup [1 ] zipimport #cleanup [1]信号
#cleanup[1 ] exceptions #cleanup [1] _warnings
#cleanup sys 内置的
#cleanup ints: 6 unfreed ints cleanup #cleanup浮动

当我执行dir时,C:\Python27\Lib\site.py*我得到以下信息:

C:\ Users \ Mimminito> dir C:\ Python27 \ Lib \ site.py *
驱动器C中的卷没有标签。
卷序列号是DAB9-A863

C:\ Python27 \ Lib目录

13/11/2010 20:08 20,389 site.py
1文件20,389字节
0目录694,910,976字节免费

有任何想法吗?

I am trying to install Python for the first time. I downloaded the following installer from the Python website: Python 2.7.1 Windows Installer (Windows binary — does not include source). I then ran the installer, selected ‘All Users’ and all was fine. I installed Python into the default location:

C:\Python27

Next, to test that Python was installed correctly, I navigated to my Python Directory, and ran the “python” command in the windows cmd prompt. It returns me the following error:

ImportError: No module named site

When I do ‘python -v’ I get the following:

#installing zipimport hook
import zipimport # builtin
#installed zipimport hook
#ImportError: No module named site #clear builtin._
#clear sys.path #clear sys.argv
#clear sys.ps1 #clear sys.ps2
#clear sys.exitfunc #clear sys.exc_type
#clear sys.exc_value #clear sys.exc_traceback
#clear sys.last_type #clear sys.last_value
#clear sys.last_traceback #clear sys.path_hooks
#clear sys.path_importer_cache #clear sys.meta_path
#clear sys.flags #clear sys.float_info
#restore sys.stdin #restore sys.stdout
#restore sys.stderr #cleanup main
#cleanup[1] zipimport #cleanup[1] signal
#cleanup[1] exceptions #cleanup[1] _warnings
#cleanup sys #cleanup builtin
#cleanup ints: 6 unfreed ints #cleanup floats

When I do dir C:\Python27\Lib\site.py* I get the following:

C:\Users\Mimminito>dir C:\Python27\Lib\site.py*
Volume in drive C has no label.
Volume Serial Number is DAB9-A863

Directory of C:\Python27\Lib

13/11/2010 20:08 20,389 site.py
1 File(s) 20,389 bytes
0 Dir(s) 694,910,976 bytes free

Any ideas?


回答 0

我已经为自己研究了近一天的问题,终于取得了突破。试试这个:

  1. 设置PYTHONPATH / PYTHONHOME变量

    右键单击开始菜单中的“ 计算机”图标,然后转到属性。在左侧标签上,转到高级系统设置。在出现的窗口中,转到“ 高级”选项卡,然后在底部单击“ 环境变量”。单击用户变量列表,然后开始键入Python,然后重复“ 系统变量”,以确保您没有为PYTHONPATH或PYTHONHOME设置错误的变量。接下来,添加新变量(我也可以在System中而不是User中使用,尽管它也可能对User也适用):PYTHONPATH,设置为C:\ Python27 \ Lib。,设置为C:\ Python27PYTHONHOME

希望这可以帮助!

I’ve been looking into this problem for myself for almost a day and finally had a breakthrough. Try this:

  1. Setting the PYTHONPATH / PYTHONHOME variables

    Right click the Computer icon in the start menu, go to properties. On the left tab, go to Advanced system settings. In the window that comes up, go to the Advanced tab, then at the bottom click Environment Variables. Click in the list of user variables and start typing Python, and repeat for System variables, just to make certain that you don’t have mis-set variables for PYTHONPATH or PYTHONHOME. Next, add new variables (I did in System rather than User, although it may work for User too): PYTHONPATH, set to C:\Python27\Lib. PYTHONHOME, set to C:\Python27.

Hope this helps!


回答 1

快速解决方案:设置PYTHONHOME和PYTHONPATH并在PATH上包含PYTHONHOME

例如,如果您安装到c:\ Python27

set PYTHONHOME=c:\Python27
set PYTHONPATH=c:\Python27\Lib
set PATH=%PYTHONHOME%;%PATH%

确保您在PYTHON *变量上没有结尾的’\’,这似乎会使它破坏。

Quick solution: set PYTHONHOME and PYTHONPATH and include PYTHONHOME on PATH

For example if you installed to c:\Python27

set PYTHONHOME=c:\Python27
set PYTHONPATH=c:\Python27\Lib
set PATH=%PYTHONHOME%;%PATH%

Make sure you don’t have a trailing ‘\’ on the PYTHON* vars, this seems to break it aswel.


回答 2

在安装Windows Python和Cygwin Python并尝试从Cygwin运行Cygwin Python之后,出现了这个问题。我export通过PYTHONHOME = / usr /和PYTHONPATH = / usr / lib / python2.7 解决了它

I was having this issue after installing both Windows Python and Cygwin Python, and trying to run Cygwin Python from Cygwin. I solved it by exporting PYTHONHOME=/usr/ and PYTHONPATH=/usr/lib/python2.7


回答 3

确保正确设置了PYTHONHOME环境变量。如果PYTHONHOME指向无效的位置或您要运行的其他Python安装,您将收到此错误。

试试这个:

C:\>set PYTHONHOME=C:\Python27
C:\>python

setx PYTHONHOME C:\Python27

将其永久设置为后续命令提示符

Make sure your PYTHONHOME environment variable is set correctly. You will receive this error if PYTHONHOME is pointing to invalid location or to another Python installation you are trying to run.

Try this:

C:\>set PYTHONHOME=C:\Python27
C:\>python

Use

setx PYTHONHOME C:\Python27

to set this permanently for subsequent command prompts


回答 4

找到site.py并将其路径添加到PYTHONPATH中。这样可以解决您的问题。

Locate site.py and add its path in PYTHONPATH. This will solve your problem.


回答 5

您是否要从Cygwin运行Windows Python?我有同样的问题。Cygwin中的Python无法导入站点。Cmd中的Python可以工作。

看起来您需要确保通过以下方式运行PYTHONHOME和PYTHONPATH cygwin -aw来使它们成为Windows路径。另外,python似乎使用了一些不正确的路径。

我想我需要通过cygwin安装python才能正常工作。

Are you trying to run Windows Python from Cygwin? I’m having the same problem. Python in Cygwin fails to import site. Python in Cmd works.

It looks like you need to make sure you run PYTHONHOME and PYTHONPATH through cygwin -aw to make them Windows paths. Also, python seems to be using some incorrect paths.

I think I’ll need to install python through cygwin to get it working.


回答 6

对于Windows 10(按照@slckin回答),可以通过以下命令在命令行中进行设置:

setx PYTHONHOME "C:\Python27"
setx PYTHONPATH "C:\Python27\Lib"
setx PATH "%PYTHONHOME%;%PATH%"

For Windows 10 (follow up on @slckin answer), this can be set through the command line with:

setx PYTHONHOME "C:\Python27"
setx PYTHONPATH "C:\Python27\Lib"
setx PATH "%PYTHONHOME%;%PATH%"

回答 7

就我而言,问题是另一个site.py文件,由于PATH设置,它比Python \ Lib中的文件更早被解决。

环境:Windows 10 Pro,Python27。

我的桌面安装了pgAdmin,它具有文件C:\ Program Files(x86)\ pgAdmin \ venv \ Lib \ site.py。由于PATH环境变量比Python更早拥有pdAdmin的目录(显然这是一个坏主意),因此首先找到pgAdmin的site.py。

解决该问题所需要做的就是在PATH中将pgAdmin的主页移到比Python晚的地方

In my case, the issue was another site.py file, that was resolved earlier than the one from Python\Lib, due to PATH setting.

Environment: Windows 10 Pro, Python27.

My desktop has pgAdmin installed, which has file C:\Program Files (x86)\pgAdmin\venv\Lib\site.py. Because PATH environment variable had pdAdmin’s home earlier than Python (apparently a bad idea in the first place), pgAdmin’s site.py was found first.

All I had to do to fix the issue was to move pgAdmin’s home later than Python, in PATH


回答 8

对我而言,发生这种情况是因为我安装了2个版本的python-python 27和python 3.3。这两个文件夹都设置了路径变量,因此存在此问题。为了解决这个问题,我将python27移到了temp文件夹,因为我对python 3.3没问题。因此,请检查诸如PATH,PYTHONHOME之类的环境变量,因为这可能是一个问题。谢谢。

For me it happened because I had 2 versions of python installed – python 27 and python 3.3. Both these folder had path variable set, and hence there was this issue. To fix, this, I moved python27 to temp folder, as I was ok with python 3.3. So do check environment variables like PATH,PYTHONHOME as it may be a issue. Thanks.


回答 9

如果有人发现非管理员用户仍无法使用它:

错误示例:

ImportError: No module named iso8601

您需要为easy_install设置“ –always-unzip”选项:

easy_install --always-unzip python-keystoneclient

它将解压缩您的egg文件,并允许导入找到em。

If somebody will find that it’s still not working under non-admin users:

Example error:

ImportError: No module named iso8601

you need to set ‘–always-unzip’ option for easy_install:

easy_install --always-unzip python-keystoneclient

It will unzip your egg files and will allow import to find em.


回答 10

ImportError: No module named site在安装python 2.7.11时遇到了同样的问题

最初我有Python2.5,PYTHONHOME路径设置为Python2.5。我将其重命名为,C:\Python27\并解决了该问题。

I went through the same issue of ImportError: No module named site while installing python 2.7.11

Initially I had Python2.5 and the PYTHONHOME path was set to Python2.5. I renamed it to C:\Python27\ and it resolved the problem.


回答 11

您可以尝试“ 开源Active Python设置”,它是Windows的出色Python安装程序。您只需要卸载并安装版本即可。

You may try the Open Source Active Python Setup which is a well done Python installer for Windows. You just have to desinstall your version and install it…


回答 12

我对slckin的答案投了赞成票。我的问题是我考虑周全,并在路径周围加了双引号。我删除了所有三个变量的双引号:PYTHONHOME,PYTHONPATH和PATH。请注意,该文件位于cmd或bat文件中,用于设置其他工具的环境。但是,双引号可能在图标设置中很有用。打字

揭示了报价在路径中的位置而不是按预期下降。我还缩短了PATH,使其长度少于256个字符。

I up voted slckin’s answer. My problem was that I was thoughtful and added double quotes around the paths. I removed the double quotes in all of the three variables: PYTHONHOME, PYTHONPATH, and PATH. Note that this was in a cmd or bat file to setup the environment for other tools. However, the double quotes may be useful in an icon setting. Typing

set

revealed that the quotes where in the path and not dropped as expected. I also shorted the PATH so that it was less than 256 characters long.


回答 13

我有一个非常依赖Python的应用程序,并随着新版本的发布保持python 2.7.x的最新性。直到2.7.11,当我遇到相同的No module named site错误时,一切都很好。我已将PYTHONHOME设置为c:\Python27且正在运行。但是仍然有一个谜,为什么在以前的版本中不需要它,现在需要这样做。而且,如果需要,安装程序为什么不设置此变量?

I have an application which relies heavily on Python and have kept up-to-date with python 2.7.x as new versions are released. Everthing has been fine until 2.7.11 when I got the same “No module named site” error. I’ve set PYTHONHOME to c:\Python27 and it’s working. But the mystery remains why this is now needed when it wasn’t with previous releases. And, if it is needed, why doesn’t the installer set this var?


回答 14

我有同样的问题。我的解决方案是修复Python安装。(这是一个新安装,因此我没想到会出现问题,但现在已解决。)

要修复(Windows 7):

  1. 转到控制面板->程序->程序和功能
  2. 单击已安装的Python版本,然后按“卸载/更改”。
  3. 请按照说明修复安装。

I had the same problem. My solution was to repair the Python installation. (It was a new installation so I did not expect a problem but now it is solved.)

To repair (Windows 7):

  1. go to Control Panel -> Programs -> Programs and Features
  2. click on the Python version installed and then press Uninstall/Change.
  3. follow the instructions to repair the installation.

回答 15

从PyYAML主页安装yaml:http ://www.pyyaml.org/wiki/PyYAML

选择适合您的OS和Python的版本。

Install yaml from the PyYAML home pagee: http://www.pyyaml.org/wiki/PyYAML

Select the appropriate version for your OS and Python.


我的Django安装在哪里?

问题:我的Django安装在哪里?

我使用Django,但需要查找默认模板和应用程序。

我不知道它的安装位置。

我怎么能找到那个?

I use Django but I need to find the default templates and applications.

I don’t know where it’s installed.

How can I find that?


回答 0

在CLI中,您可以执行以下操作:

>>> import django
>>> django
<module 'django' from '/usr/local/lib/python2.6/dist-packages/django/__init__.pyc'>

in the CLI you can do this:

>>> import django
>>> django
<module 'django' from '/usr/local/lib/python2.6/dist-packages/django/__init__.pyc'>

回答 1

$ python
>>> import django
>>> django.__file__
'/usr/local/lib/python2.7/site-packages/django/__init__.pyc'
$ python
>>> import django
>>> django.__file__
'/usr/local/lib/python2.7/site-packages/django/__init__.pyc'

回答 2

当前的最佳答案至少在Linux上不起作用。

从Django 教程中

如果您很难找到Django源文件在系统上的位置,请运行以下命令:

python -c "
import sys
sys.path = sys.path[1:]
import django
print(django.__path__)"

The current top answer doesn’t work, at least on linux.

From the Django tutorial:

If you have difficulty finding where the Django source files are located on your system, run the following command:

python -c "
import sys
sys.path = sys.path[1:]
import django
print(django.__path__)"

回答 3

在Microsft-Windows操作系统上:在python安装中的Lib / site-packages文件夹中。

On Microsft-Windows OS: In the Lib/site-packages folder inside your python installation.


回答 4

我正在描述的这种方法可跨操作系统使用…

您可以在命令行上尝试- python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"

这将为您提供基本目录。在此处输入,/django/然后在其中找到所有默认模板,管理模板等。

希望这可以帮助…

This approach I am describing works across operating systems…

You try this on your command line – python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"

This gives you the base directory. From there, type /django/ and here you find all the default templates, admin templates, etc.

Hope this helps…


回答 5

正如对@olafure的答案https://stackoverflow.com/a/12974642/4515198的评论所正确指出的那样,sys.path不需要分配。

以下内容就足够了:

python -c "import django; print(django.__path__)"

这里的-c选项用于告诉Python说“节目被传递作为字符串”(来源:命令$ python --helpbash

As the comments on @olafure’s answer https://stackoverflow.com/a/12974642/4515198 rightly say, the sys.path assignment is not required.

The following will be enough:

python -c "import django; print(django.__path__)"

Here the -c option is used to tell python that a “program is being passed in as string” (source: command $ python --help on bash)


回答 6

import django
django.__file__

输出将被赋予django文件夹的位置

'C:\\Users\\saigopi\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages\\django\\__init__.py'
import django
django.__file__

output will be given location of the django folder

'C:\\Users\\saigopi\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages\\django\\__init__.py'

回答 7

值得一提的是,如果您使用的是虚拟环境,则所有软件包都将位于项目的“ lib”下的根venv文件夹中。

Worth mentioning that if you are using a virtual env all the packages will be in your project’s root venv folder under “lib” …


回答 8

在终端上尝试一下。

$ python -v
import django # directory /home/user/.virtualenvs/myenv/local/lib/python2.7/site-packages/django
# some other imports.

Try this on an terminal.

$ python -v
import django # directory /home/user/.virtualenvs/myenv/local/lib/python2.7/site-packages/django
# some other imports.

回答 9

如果您使用的是virtualenv,则它将是:
/ home / user / path,安装django / django_directory / lib / python2.7 / site-packages / Django-1.8.1-py2.7.egg / django / contrib / admin的位置/templates/admin/base_site.html
base-site.html是默认模板。

If you are using virtualenv then it will be:
/home/user/path where you installed django/django_directory/lib/python2.7/site-packages/Django-1.8.1-py2.7.egg/django/contrib/admin/templates/admin/base_site.html
base-site.html is the default template.


python-dev安装错误:ImportError:没有名为apt_pkg的模块

问题:python-dev安装错误:ImportError:没有名为apt_pkg的模块

我是Debian用户,我想安装python-dev,但是当我以root身份在shell中运行代码时:

# aptitude install python-dev

我收到以下错误:

Traceback (most recent call last):       
  File "/usr/bin/apt-listchanges", line 28, in <module>
    import apt_pkg
ImportError: No module named apt_pkg

似乎是什么问题,我该如何解决?

I am Debian user, and I want to install python-dev, but when I run the code in the shell as a root:

# aptitude install python-dev

I get the following error:

Traceback (most recent call last):       
  File "/usr/bin/apt-listchanges", line 28, in <module>
    import apt_pkg
ImportError: No module named apt_pkg

What seems to be the problem and how can I resolve it?


回答 0

确保您有一个有效的python-apt软件包。您可以尝试再次删除并安装该软件包以解决apt_pkg.so的问题。

apt-get install python-apt

Make sure you have a working python-apt package. You could try and remove and install that package again to fix the problem with apt_pkg.so not being located.

apt-get install python-apt

回答 1

我在做的时候遇到了这个问题sudo apt-get update。我的环境是debian8,python2.7 + 3.4(默认)+ 3.5。

以下代码将仅为apt_pkg....sopython 3.5重新创建文件

sudo apt-get install python3-apt --reinstall

以下代码解决了我的问题,

cd /usr/lib/python3/dist-packages
sudo ln -s apt_pkg.cpython-{35m,34m}-x86_64-linux-gnu.so

因此,很显然,python3-apt会检查最高的python版本,而不是当前使用的python版本。

I met this problem when doing sudo apt-get update. My env is debian8, with python2.7 + 3.4(default) + 3.5.

The following code will only re-create a apt_pkg....so file for python 3.5

sudo apt-get install python3-apt --reinstall

The following code solved my problem,

cd /usr/lib/python3/dist-packages
sudo ln -s apt_pkg.cpython-{35m,34m}-x86_64-linux-gnu.so

So, obviously, python3-apt checks the highest python version, instead of the current python version in use.


回答 2

通过以下方法解决:

/usr/lib/python3/dist-packages# cp apt_pkg.cpython-34m-i386-linux-gnu.so apt_pkg.so

要么:

/usr/lib/python3/dist-packages# cp apt_pkg.cpython-35m-x86_64-linux-gnu.so apt_pkg.so

基本上,如果您No such file or directory公正ls地尝试获得正确的名字。

Solve it by this:

/usr/lib/python3/dist-packages# cp apt_pkg.cpython-34m-i386-linux-gnu.so apt_pkg.so

Or:

/usr/lib/python3/dist-packages# cp apt_pkg.cpython-35m-x86_64-linux-gnu.so apt_pkg.so

Basically, if you get a No such file or directory just ls to try to get the right name.


回答 3

在我尝试从Deadsnakes存储库中安装Python3.7之后,在Ubuntu 18.04.2上发生了这种情况。

解决方法是这个

1) cd /usr/lib/python3/dist-packages/

2) sudo ln -s apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.so

This happened to me on Ubuntu 18.04.2 after I tried to install Python3.7 from the deadsnakes repo.

Solution was this

1) cd /usr/lib/python3/dist-packages/

2) sudo ln -s apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.so


回答 4

当同时安装了新版本的python和旧版本时,通常会发生此错误。

  • Ubuntu 18.04.1随附python版本3.6.6
  • 已安装ppa:deadsnakes / python3.7.1或替代版本
  • 运行使用apt_pkg模块的命令,并显示诸如以下错误:

        from CommandNotFound.db.db import SqliteDatabase
    File "/usr/lib/python3/dist-packages/CommandNotFound/db/db.py", line 5, in <module>
        import apt_pkg
    

当我们安装带有apt的非发行版python3版本时,会将共享模块目录设置为python3的共享目录,通常是/usr/lib/python3

在大多数情况下,这是可以的,但是在某些情况下,不同版本的python会比其他python版本依赖不同的库或共享对象/库,因此正如其他答案所指出的那样,我们需要将.SO链接到正确的python版本。因此,如果我们在64位系统上安装了python3.6,则apt_pkg .SO链接为

sudo ln -s apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.so

但是问题在于,当我们安装较新的python版本时,链接将更新为指向最新的python版本,这将导致找不到apt_pkg模块的错误。通过检查发行版附带的python版本,您可以创建上述链接。或者,我们使用一种方法来为命令提供选择python版本以链接.SO的选择,例如;

sudo ln -s apt_pkg.cpython-{36m,35m,34m}-x86_64-linux-gnu.so apt_pkg.so

因为python会创建到最新安装的python版本的链接,所以我们给命令提供了从3个python版本中进行选择的选项,它将选择给定的最高版本。

This error will often occur when a newer version of python has been installed alongside an older version e.g;

  • Ubuntu 18.04.1 ships with python version 3.6.6
  • Installed ppa:deadsnakes/python3.7.1 or alternative
  • Run a command that uses the apt_pkg module and get an error such as;

        from CommandNotFound.db.db import SqliteDatabase
    File "/usr/lib/python3/dist-packages/CommandNotFound/db/db.py", line 5, in <module>
        import apt_pkg
    

When we install a non-distro python3 version with apt it will set a shared module directory to be that of python3 most usually it will be /usr/lib/python3.

Most of the time this will be ok, but under some circumstances the different versions of python rely on different libraries or shared objects/libraries than the other python version does, so as other answers have pointed out we need to link the .SO to the correct python version. So if we have python3.6 installed on a 64bit system then the apt_pkg .SO link would be

sudo ln -s apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.so

But the problem lies in the fact that when we install a newer python version the link will update to point to the newest python version, which leads to the error of apt_pkg module not being found. By checking which version of python ships with your distro you can create the link as shown above. Or we use a method to offer the command a choice of python versions to link the .SO such as;

sudo ln -s apt_pkg.cpython-{36m,35m,34m}-x86_64-linux-gnu.so apt_pkg.so

Because python will create this link to the newest installed python version we give the command the option to choose from 3 python versions, of which it will choose the highest version given.


回答 5

@ user8178061的解决方案效果很好,但是我对python3.7Ubuntu的版本做了一些修改

我更换了apt_pkg.cpython-3m-i386-linux-gnu.soapt_pkg.cpython-36m-x86_64-linux-gnu.so

这里执行两个命令:

cd /usr/lib/python3/dist-packages

sudo cp apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.so

The solution of @user8178061 worked well but I did it with some modifications for my version wich is python3.7 with Ubuntu

I replaced the apt_pkg.cpython-3m-i386-linux-gnu.so with apt_pkg.cpython-36m-x86_64-linux-gnu.so

Here the two commands to execute:

cd /usr/lib/python3/dist-packages

sudo cp apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.so


回答 6

在ubuntu18.04上更新python3.7之后,这对我有用

cd /usr/lib/python3/dist-packages
sudo cp apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.so

This worked for me on after updating python3.7 on ubuntu18.04

cd /usr/lib/python3/dist-packages
sudo cp apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.so

回答 7

由于某种原因apt_pkg.so,python3 dist-packages目录中缺少我的安装。(apt_pkg.cpython-33m-x86_64-linux-gnu.so在那里?!),但是,我不得不作出一个符号链接apt_pkg.so -> apt_pkg.cpython-33m-x86_64-linux-gnu.so/usr/lib/python3/dist-packages

我不确定我的升级是否中断,或者为什么会这样。尝试升级后发生(精确-> raring->定量升级)

For some reason my install was missing apt_pkg.so in the python3 dist-packages dir. (apt_pkg.cpython-33m-x86_64-linux-gnu.so was there?!) but and I had to make a symlink apt_pkg.so -> apt_pkg.cpython-33m-x86_64-linux-gnu.so in /usr/lib/python3/dist-packages

I’m not sure whether my upgrade was broken or why this was the case. It occured after trying to upgrade (precise->raring->quantal upgrade)


回答 8

  1. 检查您的默认Python 3版本:
python --version
Python 3.7.5
  1. cd进入/usr/lib/python3/dist-packages并检查apt_pkg.*文件。您会发现默认Python版本没有:
ll apt_pkg.*
apt_pkg.cpython-36m-x86_64-linux-gnu.so
  1. 创建符号链接:
sudo ln -s apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.cpython-37m-x86_64- linux-gnu.so 
  1. Check your default Python 3 version:
python --version
Python 3.7.5
  1. cd into /usr/lib/python3/dist-packages and check the apt_pkg.* files. You will find that there is none for your default Python version:
ll apt_pkg.*
apt_pkg.cpython-36m-x86_64-linux-gnu.so
  1. Create the symlink:
sudo ln -s apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.cpython-37m-x86_64- linux-gnu.so 

回答 9

不得已的方法是,sudo cp /usr/lib/python3/dist-packages/apt_pkg.cpython-35m-x86_64-linux-gnu.so /usr/lib/python3/dist-packages/apt_pkg.cpython-36m-x86_64-linux-gnu.so 如果该ln命令对您来说太多了,或者由于某种原因魔术无法正常工作。

cpmv如果您仅致力于使用一个Python版本,则也可以使用上述方法。

A last resort is sudo cp /usr/lib/python3/dist-packages/apt_pkg.cpython-35m-x86_64-linux-gnu.so /usr/lib/python3/dist-packages/apt_pkg.cpython-36m-x86_64-linux-gnu.so if the ln command is too much for you or somehow magically doesn’t work.

cp above can also be mv if you are only dedicated to using one Python version.


回答 10

如果您使用的是python 3.7,请通过更新Alternatives将其降级为python 3.6,这对我有用

sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 1

sudo update-alternatives --config python3

if you’re using python 3.7 downgrade it to python 3.6 by updating Alternatives, This worked for me

sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 1

sudo update-alternatives --config python3

回答 11

如果您使用的是Python 3.5,请降级为3.4。这是最安全的举动。

在下面,/usr/lib/python3/dist-packages您将看到*34m*不能使用哪个python 3.5。zhazha回答了它的符号链接。

If you’re using python 3.5, downgrade to 3.4. That’s the safest move to do.

Under /usr/lib/python3/dist-packages you’ll see *34m* which python 3.5 can’t use. zhazha answer symlink to it.


回答 12

除了为其建立符号链接外apt_pkg.so,您可能还希望以与之apt_inst.so相同的方式进行apt_pkg.so

ln -s apt_inst.cpython-35m-x86_64-linux-gnu.so apt_inst.so 

In addition to making a symbolic link for apt_pkg.so, you may want to make apt_inst.so in the same manner of apt_pkg.so.

ln -s apt_inst.cpython-35m-x86_64-linux-gnu.so apt_inst.so 

回答 13

我看到每个人都在说如何通过奇怪的复制等方式修复它,但是没人真正说出为什么会出现此问题。

因此,让我解释一下,对于像我这样的人,不想仅仅因为SO上的某人告诉了他们而弄乱系统文件。


问题是:

  • 许多系统脚本都将python3 shebang硬编码到其中。您可以自己检查:
~$ grep -R "\#\!/usr/bin/python3" /usr/lib/*

/usr/lib/cnf-update-db:#!/usr/bin/python3
/usr/lib/command-not-found:#!/usr/bin/python3
/usr/lib/cups/filter/pstotiff:#!/usr/bin/python3
/usr/lib/cups/filter/rastertosag-gdi:#!/usr/bin/python3 -u
grep: /usr/lib/cups/backend/cups-brf: Permission denied
/usr/lib/cups/backend/hpfax:#!/usr/bin/python3
/usr/lib/language-selector/ls-dbus-backend:#!/usr/bin/python3
/usr/lib/python3/dist-packages/language_support_pkgs.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/softwareproperties/MirrorTest.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/installdriver.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/openprinting.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/xmldriverprefs.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/smburi.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/ppds.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/debug.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/DistUpgrade/dist-upgrade.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/CommandNotFound/db/creator.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/CommandNotFound/db/db.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/Quirks/quirkreader.py:#!/usr/bin/python3
grep: /usr/lib/ssl/private: Permission denied
/usr/lib/system-service/system-service-d:#!/usr/bin/python3
/usr/lib/ubuntu-release-upgrader/check-new-release-gtk:#!/usr/bin/python3
/usr/lib/ubuntu-release-upgrader/do-partial-upgrade:#!/usr/bin/python3
/usr/lib/ubuntu-release-upgrader/check-new-release:#!/usr/bin/python3
/usr/lib/update-notifier/package-data-downloader:#!/usr/bin/python3
/usr/lib/update-notifier/backend_helper.py:#!/usr/bin/python3
/usr/lib/update-notifier/apt_check.py:#!/usr/bin/python3
/usr/lib/update-notifier/apt-check:#!/usr/bin/python3

  • python apt package python-apt/python3-apt是系统软件包,因此它是默认系统python

因此,这些脚本将始终获得当前链接到的版本python3,但是由于apt软件包不存在而失败。


常规解决方案:永远不要更改默认python3链接。曾经 这也适用于python链接-如果应用程序是使用Python2编写的,但其中的某些旧语法元素在Python3中不起作用,则该应用程序将无法工作。

[我的终端打破了这种方式,因为我使用了终结者,终结者显然是用Python2.7编写的,与Python3不兼容。]


这里介绍的解决方案建议复制/链接apt软件包文件或更改python3链接。

让我们分析一下:

  1. 复制/链接apt包

应该不是问题,因为从Python3.4开始,所有python脚本也都可以在较新的版本上运行。

至今。但是,如果您将系统保留足够长的时间,将来可能会中断。

  1. python3回链接

这是一个很好的解决方案,因为我们可以回到“从不更改链接”


“但是我喜欢只打python!” – 我也喜欢这个!这就是我首先解决这个问题的方法!

  1. 通常,应该避免手动更改系统链接-update-alternatives而是使用它来链接不同的版本。这适用于具有多个版本的任何应用。这仍然会破坏那些系统脚本(因为它确实会更改链接),但是您可以轻松地来回切换,而不必担心将链接和目标按正确的顺序放置或输入错误。

  2. 考虑为链接或别名使用python/以外的其他名称python3

  3. 或将自己的python/python3链接添加到PATH(就像虚拟环境一样),而无需更改系统链接。

I see everyone saying how to fix it with strange copying etc, but no one really said why the problem occurs.

So let me explain, for those of you who like me don’t want to mess with system files only because someone on SO told them so.


The problem is that:

  • many system scripts have python3 shebang hardcoded into them. You can check it yourself:
~$ grep -R "\#\!/usr/bin/python3" /usr/lib/*

/usr/lib/cnf-update-db:#!/usr/bin/python3
/usr/lib/command-not-found:#!/usr/bin/python3
/usr/lib/cups/filter/pstotiff:#!/usr/bin/python3
/usr/lib/cups/filter/rastertosag-gdi:#!/usr/bin/python3 -u
grep: /usr/lib/cups/backend/cups-brf: Permission denied
/usr/lib/cups/backend/hpfax:#!/usr/bin/python3
/usr/lib/language-selector/ls-dbus-backend:#!/usr/bin/python3
/usr/lib/python3/dist-packages/language_support_pkgs.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/softwareproperties/MirrorTest.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/installdriver.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/openprinting.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/xmldriverprefs.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/smburi.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/ppds.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/debug.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/DistUpgrade/dist-upgrade.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/CommandNotFound/db/creator.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/CommandNotFound/db/db.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/Quirks/quirkreader.py:#!/usr/bin/python3
grep: /usr/lib/ssl/private: Permission denied
/usr/lib/system-service/system-service-d:#!/usr/bin/python3
/usr/lib/ubuntu-release-upgrader/check-new-release-gtk:#!/usr/bin/python3
/usr/lib/ubuntu-release-upgrader/do-partial-upgrade:#!/usr/bin/python3
/usr/lib/ubuntu-release-upgrader/check-new-release:#!/usr/bin/python3
/usr/lib/update-notifier/package-data-downloader:#!/usr/bin/python3
/usr/lib/update-notifier/backend_helper.py:#!/usr/bin/python3
/usr/lib/update-notifier/apt_check.py:#!/usr/bin/python3
/usr/lib/update-notifier/apt-check:#!/usr/bin/python3

  • python apt package python-apt/python3-apt is a system package, so it’s for default system python

Thus, the scripts will always get the version currently linked to python3, but fail because the apt package is not present.


General solution: NEVER change default python3 link. Ever. This also applies to python link – if an app was written in Python2 with some old syntax elements that don’t work in Python3, the app will not work.

[My terminal broke that way because I use Terminator, which is apparently written in Python2.7 not compatible with Python3.]


Solutions presented here either suggest copying/linking the apt package files or changing python3 link.

Let’s analyse both:

  1. Copying/linking the apt package

This shouldn’t be a problem because from around Python3.4 all python scripts work on newer versions as well.

So far. But it may break in the future – if you keep your system long enough.

  1. Changing python3 link back

This is a great solution because we can get back to “never ever changing the link”


“But I like having to type just python!” – I like it too! That’s how I got to this problem in the first place!

  1. In general, you should avoid manually changing system links – use update-alternatives instead to link different versions. This applies to any app with many versions. This will still break those system scripts (because it does change the link), but you can switch back and forth easily, without worrying whether you put link and dest in the right order or made a typo.

  2. Consider using other name than python/python3 for your link or alias.

  3. Or add your own python/python3 link to PATH (just like virtual environments do), without changing system links.


回答 14

Windows 10 WSL v1(Ubuntu 16.04.6 LTS)

这个reddit答案(稍加修改对我有用

sudo ln -sfn /usr/lib/python3/dist-packages/apt_pkg.cpython-35m-x86_64-linux-gnu.so apt_pkg.so

Windows 10 WSL v1 (Ubuntu 16.04.6 LTS)

This reddit answer (slightly modified worked for me)

sudo ln -sfn /usr/lib/python3/dist-packages/apt_pkg.cpython-35m-x86_64-linux-gnu.so apt_pkg.so


回答 15

请查看以下文档。肯定会解决问题。 http://www.programmersought.com/article/55001874709/

Please review the following documentation. It will definitely solve the problem. http://www.programmersought.com/article/55001874709/


回答 16

没有一个答案对我有用(我正在使用Ubuntu 16.04和Python 3.6)。因此,我终于解决了以下问题:

1-连接到服务器的FTP

2-转到文件夹“ / usr / lib / python3 / dist-packages /”

3-复制文件“ apt_pkg.cpython-3 5 m-x86_64-linux-gnu.so”

4-将此重复文件重命名为“ apt_pkg.cpython-3 6 m-x86_64-linux-gnu.so”

而已!

None of the answers worked for me (I am using Ubuntu 16.04 and Python 3.6). So I finally solved the issue as following:

1- connect to the FTP of the server

2- go to the folder “/usr/lib/python3/dist-packages/”

3- duplicate the file “apt_pkg.cpython-35m-x86_64-linux-gnu.so”

4- rename this duplicated file to “apt_pkg.cpython-36m-x86_64-linux-gnu.so”

That’s it!


回答 17

我在Ubuntu 16.04上,并已升级到Python 3.7。这是我尝试添加PPA时遇到的错误

    sudo add-apt-repository ppa:ubuntu-toolchain-r/test                                           
Traceback (most recent call last):
  File "/usr/bin/add-apt-repository", line 11, in <module>
    from softwareproperties.SoftwareProperties import SoftwareProperties, shortcut_handler
  File "/usr/lib/python3/dist-packages/softwareproperties/SoftwareProperties.py", line 27, in <module>
    import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'

我可以通过创建以下符号链接来与我的初始python 3.4 apt_pkg.cpython-34m-x86_64-linux-gnu.so建立符号链接来解决此错误

sudo ln -s apt_pkg.cpython-34m-x86_64-linux-gnu.so apt_pkg.so

I’m on Ubuntu 16.04, and upgraded to Python 3.7. Here is the error that I had when trying to add a PPA

    sudo add-apt-repository ppa:ubuntu-toolchain-r/test                                           
Traceback (most recent call last):
  File "/usr/bin/add-apt-repository", line 11, in <module>
    from softwareproperties.SoftwareProperties import SoftwareProperties, shortcut_handler
  File "/usr/lib/python3/dist-packages/softwareproperties/SoftwareProperties.py", line 27, in <module>
    import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'

I was able to fix this error by making symbolic link with my initial python 3.4 apt_pkg.cpython-34m-x86_64-linux-gnu.so by creating the following symbolic link

sudo ln -s apt_pkg.cpython-34m-x86_64-linux-gnu.so apt_pkg.so

回答 18

请尝试通过设置区域设置变量来解决此问题:

export LC_ALL="en_US.UTF-8"

export LC_CTYPE="en_US.UTF-8"

Please try to fix this by setting the locale variables:

export LC_ALL="en_US.UTF-8"

export LC_CTYPE="en_US.UTF-8"

回答 19

以防万一,这终于解决了这个问题,这显然是python版本冲突所致,方法是重定向链接python3,然后将其重定向到正确的python版本:

sudo rm /usr/bin/python3
sudo ln -s /usr/bin/python3.4

您可能需要输入正确的python版本,找到以下版本:

python3 -V

Just in case it helps another, I finally solved this problem, that was apparently caused by python version conflicts, by redirecting the link python3, then redirecting it to the right python version:

sudo rm /usr/bin/python3
sudo ln -s /usr/bin/python3.4

You may need to enter the correct python version, found with:

python3 -V

无法在ubuntu中将默认python版本设置为python3

问题:无法在ubuntu中将默认python版本设置为python3

我试图将默认python版本设置为python3in Ubuntu 16.04。默认情况下为python2(2.7)。我遵循以下步骤:

update-alternatives --remove python /usr/bin/python2
update-alternatives --install /usr/bin/python python /usr/bin/python3

但是第二条语句出现以下错误,

rejeesh@rejeesh-Vostro-1015:~$ update-alternatives --install /usr/bin/python python /usr/bin/python3
update-alternatives: --install needs <link> <name> <path> <priority>

Use 'update-alternatives --help' for program usage information.   

我是Ubuntu的新手,我不知道自己在做什么错。

I was trying to set default python version to python3 in Ubuntu 16.04. By default it is python2 (2.7). I followed below steps :

update-alternatives --remove python /usr/bin/python2
update-alternatives --install /usr/bin/python python /usr/bin/python3

but I’m getting the following error for the second statement,

rejeesh@rejeesh-Vostro-1015:~$ update-alternatives --install /usr/bin/python python /usr/bin/python3
update-alternatives: --install needs <link> <name> <path> <priority>

Use 'update-alternatives --help' for program usage information.   

I’m new to Ubuntu and Idon’t know what I’m doing wrong.


回答 0

打开您的.bashrc文件nano ~/.bashrcalias python=python3在文件顶部的新行上键入,然后使用ctrl + o保存文件并使用ctrl + x关闭文件。然后,返回您的命令行类型source ~/.bashrc。现在,您的别名应该是永久的。

编辑:

对于更新替代方案,优先级是整数。优先级表示应该首先使用哪个程序。文章总结说起来相当不错。

EDIT:

I wrote this when I was young an naive, update-alternatives is the better way to do this. See @Pardhu’s answer.

Open your .bashrc file nano ~/.bashrc. Type alias python=python3 on to a new line at the top of the file then save the file with ctrl+o and close the file with ctrl+x. Then, back at your command line type source ~/.bashrc. Now your alias should be permanent.


回答 1

提到的第二行可以更改为

update-alternatives --install /usr/bin/python python /usr/bin/python3 10

的路径优先级为10 python3。编辑.bashrc文件的缺点是,当与结合使用命令时,它将不起作用sudo

更新:sudo在运行以下命令时使用:

sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 10

The second line mentioned can be changed to

update-alternatives --install /usr/bin/python python /usr/bin/python3 10

This gives a priority of 10 for the path of python3. The disadvantage of editing .bashrc file is that it will not work while using the commands with sudo.

Update: Please use sudo while running the command like this:

sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 10


回答 2

将Ubuntu 3.04中的默认Python 3.6.8更改为Python 3.7。

安装Python 3.7

安装Python3.7并将其配置为默认解释器的步骤。

  1. 使用apt-get安装python3.7软件包

    sudo apt-get install python3.7

  2. 将Python3.6和Python 3.7添加到 update-alternatives

sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.7 2
  1. 更新Python 3以指向Python 3.7

    sudo update-alternatives --config python3 为Python 3.7输入2

  2. 测试python版本

python3 --v
Python 3.7.1 

To change Python 3.6.8 as the default in Ubuntu 18.04 to Python 3.7.

Install Python 3.7

Steps to install Python3.7 and configure it as the default interpreter.

  1. Install the python3.7 package using apt-get

    sudo apt-get install python3.7

  2. Add Python3.6 & Python 3.7 to update-alternatives

sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.7 2
  1. Update Python 3 to point to Python 3.7

    sudo update-alternatives --config python3 Enter 2 for Python 3.7

  2. Test the version of python

python3 --version
Python 3.7.1 

回答 3

要更改为python3,可以在terminal中使用以下命令alias python=python3

To change to python3, you can use the following command in terminal alias python=python3.


回答 4

一种简单安全的方法是使用别名。将其放入〜/ .bashrc文件中:如果您使用gedit编辑器

gedit〜/ .bashrc

进入bashrc文件,然后在bashrc文件的顶部进行以下更改。

别名python = python3

在文件中添加以上内容之后。运行以下命令

源〜/ .bash_aliases或源〜/ .bashrc

例:

$ python-版本

Python 2.7.6

$ python3-版本

Python 3.4.3

$别名python = python3

$ python-版本

Python 3.4.3

A simple safe way would be to use an alias. Place this into ~/.bashrc file: if you have gedit editor use

gedit ~/.bashrc

to go into the bashrc file and then at the top of the bashrc file make the following change.

alias python=python3

After adding the above in the file. run the below command

source ~/.bash_aliases or source ~/.bashrc

example:

$ python –version

Python 2.7.6

$ python3 –version

Python 3.4.3

$ alias python=python3

$ python –version

Python 3.4.3


回答 5

另外,您还可以为pip添加一个别名(在.bashrc或bash_aliases中):

别名pip =’pip3′

许多人发现python3的全新安装实际上指向python3.x,因此您可能需要:

别名pip =’pip3.6′
别名python =’python3.6′

As an added extra, you can add an alias for pip as well (in .bashrc or bash_aliases):

alias pip=’pip3′

You many find that a clean install of python3 actually points to python3.x so you may need:

alias pip=’pip3.6′
alias python=’python3.6′


回答 6

首先安装python3和pip3

sudo apt-get install python3 python3-pip

然后在终端运行

alias python=python3

检查计算机中的python版本。

python --version

At First Install python3 and pip3

sudo apt-get install python3 python3-pip

then in your terminal run

alias python=python3

Check the version of python in your machine.

python --version

回答 7

如果您具有Ubuntu Focal(20.20),则可以安装python-is-python3

sudo apt-get install python-is-python3

替换符号链接/usr/bin/python以指向/usr/bin/python3.8

If you have Ubuntu 20.04 LTS (Focal Fossa) you can install python-is-python3:

sudo apt install python-is-python3

which replaces the symlink in /usr/bin/python to point to /usr/bin/python3.


回答 8

就像说的那样 update-alternatives --install需要<link> <name> <path>和<priority>参数。

您具有链接(/usr/bin/python),名称(python)和路径(/usr/bin/python3),但缺少优先级。

update-alternatives --help 说:

<priority>是整数;数字更大的选项在自动模式下具有更高的优先级。

所以100在末尾放一个

As it says, update-alternatives --install needs <link> <name> <path> and <priority> arguments.

You have link (/usr/bin/python), name (python), and path (/usr/bin/python3), you’re missing priority.

update-alternatives --help says:

<priority> is an integer; options with higher numbers have higher priority in automatic mode.

So just put a 100 or something at the end


回答 9

cd ~
gedit .bash_aliases

然后写

alias python=python3

要么

alias python='/usr/bin/python3'

保存文件,关闭终端,然后再次打开。
您现在应该很好!链接

Do

cd ~
gedit .bash_aliases

then write either

alias python=python3

or

alias python='/usr/bin/python3'

Save the file, close the terminal and open it again.
You should be fine now! Link


回答 10

只需按照以下步骤操作,即可将默认python更改为新升级的python版本。对我来说很好。

  • sudo apt-install python3.7 安装所需的最新版本的python
  • cd /usr/bin 输入安装了python的根目录
  • sudo unlink pythonsudo unlink python3。取消链接当前的默认python
  • sudo ln -sv /usr/bin/python3.7 python 链接新下载的python版本
  • python --version 检查新的python版本,您一切顺利

Just follow these steps to help change the default python to the newly upgrade python version. Worked well for me.

  • sudo apt-install python3.7 Install the latest version of python you want
  • cd /usr/bin Enter the root directory where python is installed
  • sudo unlink python or sudo unlink python3 . Unlink the current default python
  • sudo ln -sv /usr/bin/python3.7 python Link the new downloaded python version
  • python --version Check the new python version and you’re good to go

回答 11

对于另一种仅限于当前用户的非侵入式方法:

# First, make $HOME/bin, which will be automatically added to user's PATH
mkdir -p ~/bin
# make link actual python binaries
ln -s $(which python3) python
ln -s $(which pip3) pip

python pip 将在新的外壳中准备好。

For another non-invasive, current-user only approach:

# First, make $HOME/bin, which will be automatically added to user's PATH
mkdir -p ~/bin
# make link actual python binaries
ln -s $(which python3) python
ln -s $(which pip3) pip

python pip will be ready in a new shell.


回答 12

从获取python路径

ls /usr/bin/python*

然后设置你的python版本

alias python="/usr/bin/python3"

get python path from

ls /usr/bin/python*

then set your python version

alias python="/usr/bin/python3"

回答 13

适用于所有用户的ubuntu 18.04中的最佳方法是

sudo vim /etc/bash.bashrc
add lines
alias python=python3
alias pip=pip3

保存更改并重新启动。

重新启动后,系统中的python 3版本以及python 2.7都将作为默认版本。如果您使用的是python 3的多个版本,则可以通过在别名中说以下内容来更加具体。

sudo vim /etc/bash.bashrc
add lines
alias python=python3.6
alias pip=pip3.6

The best way in ubuntu 18.04 which will work for all users is

sudo vim /etc/bash.bashrc
add lines
alias python=python3
alias pip=pip3

Save the changes and restart .

After restart what ever version of python 3 you have in the system along with python 2.7 will be taken as default. You could be more specific by saying the following in alias if you have multiple version of python 3.

sudo vim /etc/bash.bashrc
add lines
alias python=python3.6
alias pip=pip3.6

回答 14

只需删除python-is-python2

sudo apt purge python-is-python2

并安装python-is-python3

sudo apt install python-is-python3

它将自动过渡到新的python3。(可选)您可以稍后删除其余软件包:

sudo apt autoremove && sudo apt autoclean

Simply remove python-is-python2:

sudo apt purge python-is-python2

And install python-is-python3:

sudo apt install python-is-python3

It will automate the process of transition to new python3. Optionally you can get rid of remaining packages later:

sudo apt autoremove && sudo apt autoclean

回答 15

要将Python 3.6.8从Python 2.7更改为Ubuntu 18.04中的默认设置,可以尝试使用命令行工具update-alternatives

sudo update-alternatives --config python

如果出现错误“ python没有替代品”,请使用以下命令自己设置替代品:

sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 2

相应地将路径更改为/usr/bin/python3所需的python版本。

优先级指定的最后一个参数表示,如果未进行手动替代选择,则将设置优先级最高的替代项。在我们的示例中,我们为设置了优先级2,/usr/bin/python3.6.8因此/usr/bin/python3.6.8update-alternatives命令自动将其设置为默认python版本。

我们可以随时使用以下命令在上面列出的python替代版本之间切换,并输入选择编号:

update-alternatives --config python

To change Python 3.6.8 as the default in Ubuntu 18.04 from Python 2.7 you can try the command line tool update-alternatives.

sudo update-alternatives --config python

If you get the error “no alternatives for python” then set up an alternative yourself with the following command:

sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 2

Change the path /usr/bin/python3 to your desired python version accordingly.

The last argument specified it priority means, if no manual alternative selection is made the alternative with the highest priority number will be set. In our case we have set a priority 2 for /usr/bin/python3.6.8 and as a result the /usr/bin/python3.6.8 was set as default python version automatically by update-alternatives command.

we can anytime switch between the above listed python alternative versions using below command and entering a selection number:

update-alternatives --config python

回答 16

首先,确保您的计算机上安装了Python3

转到终端并输入:

cd ~/ 转到您的主目录

如果尚未设置,请.bash_profile键入touch .bash_profile以创建.bash_profile。

或者,键入open -e .bash_profile以编辑文件。

复制并保存alias python=python3在.bash_profile中。

关闭并重新打开您的终端。然后键入以下命令以检查是否 Python3现在是您的默认版本:

python --version

您应该看到python 3.xy是您的默认版本。

干杯!

At first, Make sure Python3 is installed on your computer

Go to your terminal and type:

cd ~/ to go to your home directory

If you didn’t set up your .bash_profile yet, type touch .bash_profile to create your .bash_profile.

Or, type open -e .bash_profile to edit the file.

Copy and save alias python=python3 in the .bash_profile.

Close and reopen your Terminal. Then type the following command to check if Python3 is your default version now:

python --version

You should see python 3.x.y is your default version.

Cheers!


用pip安装PIL

问题:用pip安装PIL

我正在尝试使用以下命令安装PIL(Python Imaging Library):

sudo pip install pil

但我收到以下消息:

Downloading/unpacking PIL
  You are installing a potentially insecure and unverifiable file. Future versions of pip will default to disallowing insecure files.
  Downloading PIL-1.1.7.tar.gz (506kB): 506kB downloaded
  Running setup.py egg_info for package PIL
    WARNING: '' not a valid package name; please use only.-separated package names in setup.py

Installing collected packages: PIL
  Running setup.py install for PIL
    WARNING: '' not a valid package name; please use only.-separated package names in setup.py
    --- using frameworks at /System/Library/Frameworks
    building '_imaging' extension
    clang -fno-strict-aliasing -fno-common -dynamic -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch i386 -arch x86_64 -pipe -IlibImaging -I/System/Library/Frameworks/Python.framework/Versions/2.7/include -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _imaging.c -o build/temp.macosx-10.8-intel-2.7/_imaging.o
    unable to execute clang: No such file or directory
    error: command 'clang' failed with exit status 1
    Complete output from command /usr/bin/python -c "import setuptools;__file__='/private/tmp/pip_build_root/PIL/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-AYrxVD-record/install-record.txt --single-version-externally-managed:
    WARNING: '' not a valid package name; please use only.-separated package names in setup.py

running install

running build

.
.
.
.

copying PIL/XVThumbImagePlugin.py -> build/lib.macosx-10.8-intel-2.7

running build_ext

--- using frameworks at /System/Library/Frameworks

building '_imaging' extension

creating build/temp.macosx-10.8-intel-2.7

creating build/temp.macosx-10.8-intel-2.7/libImaging

clang -fno-strict-aliasing -fno-common -dynamic -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch i386 -arch x86_64 -pipe -IlibImaging -I/System/Library/Frameworks/Python.framework/Versions/2.7/include -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _imaging.c -o build/temp.macosx-10.8-intel-2.7/_imaging.o

unable to execute clang: No such file or directory

error: command 'clang' failed with exit status 1

----------------------------------------
Cleaning up

您能帮我安装PIL吗?

I am trying to install PIL (the Python Imaging Library) using the command:

sudo pip install pil

but I get the following message:

Downloading/unpacking PIL
  You are installing a potentially insecure and unverifiable file. Future versions of pip will default to disallowing insecure files.
  Downloading PIL-1.1.7.tar.gz (506kB): 506kB downloaded
  Running setup.py egg_info for package PIL
    WARNING: '' not a valid package name; please use only.-separated package names in setup.py

Installing collected packages: PIL
  Running setup.py install for PIL
    WARNING: '' not a valid package name; please use only.-separated package names in setup.py
    --- using frameworks at /System/Library/Frameworks
    building '_imaging' extension
    clang -fno-strict-aliasing -fno-common -dynamic -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch i386 -arch x86_64 -pipe -IlibImaging -I/System/Library/Frameworks/Python.framework/Versions/2.7/include -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _imaging.c -o build/temp.macosx-10.8-intel-2.7/_imaging.o
    unable to execute clang: No such file or directory
    error: command 'clang' failed with exit status 1
    Complete output from command /usr/bin/python -c "import setuptools;__file__='/private/tmp/pip_build_root/PIL/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-AYrxVD-record/install-record.txt --single-version-externally-managed:
    WARNING: '' not a valid package name; please use only.-separated package names in setup.py

running install

running build

.
.
.
.

copying PIL/XVThumbImagePlugin.py -> build/lib.macosx-10.8-intel-2.7

running build_ext

--- using frameworks at /System/Library/Frameworks

building '_imaging' extension

creating build/temp.macosx-10.8-intel-2.7

creating build/temp.macosx-10.8-intel-2.7/libImaging

clang -fno-strict-aliasing -fno-common -dynamic -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch i386 -arch x86_64 -pipe -IlibImaging -I/System/Library/Frameworks/Python.framework/Versions/2.7/include -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _imaging.c -o build/temp.macosx-10.8-intel-2.7/_imaging.o

unable to execute clang: No such file or directory

error: command 'clang' failed with exit status 1

----------------------------------------
Cleaning up…

Could you please help me to install PIL??


回答 0

  1. 如上所述安装Xcode和Xcode命令行工具。
  2. 请改用Pillow,因为PIL基本已失效。枕头是PIL的保养品。

https://pypi.python.org/pypi/Pillow/2.2.1

pip install Pillow

如果您同时安装了两个Python,并且想为Python3安装此代码,请执行以下操作:

python3 -m pip install Pillow
  1. Install Xcode and Xcode Command Line Tools as mentioned.
  2. Use Pillow instead, as PIL is basically dead. Pillow is a maintained fork of PIL.

https://pypi.python.org/pypi/Pillow/2.2.1

pip install Pillow

If you have both Pythons installed and want to install this for Python3:

python3 -m pip install Pillow

回答 1

这对我有用:

apt-get install python-dev
apt-get install libjpeg-dev
apt-get install libjpeg8-dev
apt-get install libpng3
apt-get install libfreetype6-dev
ln -s /usr/lib/i386-linux-gnu/libfreetype.so /usr/lib
ln -s /usr/lib/i386-linux-gnu/libjpeg.so /usr/lib
ln -s /usr/lib/i386-linux-gnu/libz.so /usr/lib

pip install PIL  --allow-unverified PIL --allow-all-external

This works for me:

apt-get install python-dev
apt-get install libjpeg-dev
apt-get install libjpeg8-dev
apt-get install libpng3
apt-get install libfreetype6-dev
ln -s /usr/lib/i386-linux-gnu/libfreetype.so /usr/lib
ln -s /usr/lib/i386-linux-gnu/libjpeg.so /usr/lib
ln -s /usr/lib/i386-linux-gnu/libz.so /usr/lib

pip install PIL  --allow-unverified PIL --allow-all-external

回答 2

使用apt install非常简单,使用此命令即可完成

sudo apt-get install python-PIL

要么

sudo pip install pillow

要么

sudo easy_install pillow

It is very simple using apt install use this command to get it done

sudo apt-get install python-PIL

or

sudo pip install pillow

or

sudo easy_install pillow

回答 3

在Mac OS X上,使用以下命令:

sudo pip install https://effbot.org/media/downloads/Imaging-1.1.7.tar.gz

On Mac OS X, use this command:

sudo pip install https://effbot.org/media/downloads/Imaging-1.1.7.tar.gz

回答 4

您应该描述安装在这里

pip install image

You should install as described here:

pip install image

回答 5

我从这里的讨论中得到了答案:

我试过了

pip install --no-index -f http://dist.plone.org/thirdparty/ -U PIL

而且有效。

I got the answer from a discussion here:

I tried

pip install --no-index -f http://dist.plone.org/thirdparty/ -U PIL

and it worked.


回答 6

安装

pip install Pillow

然后,只需导入文件,例如

from PIL import Image

我正在使用Windows。它为我工作。

注意

Pillow是Python Imaging Library的功能替代品。要使用Pillow运行现有的PIL兼容代码,需要对其进行修改以从PIL命名空间而不是全局命名空间导入Imaging模块。

即更改:

import Image

至:

from PIL import Image

https://pypi.org/project/枕头/2.2.1/

Install

pip install Pillow

Then, Just import in your file like,

from PIL import Image

I am using windows. It is working for me.

NOTE:

Pillow is a functional drop-in replacement for the Python Imaging Library. To run your existing PIL-compatible code with Pillow, it needs to be modified to import the Imaging module from the PIL namespace instead of the global namespace.

i.e. change:

import Image

to:

from PIL import Image

https://pypi.org/project/Pillow/2.2.1/


回答 7

我认为您在Mac上。请参阅如何在Mac OS X 10.7.2 Lion上安装PIL

如果使用[homebrew] [],则可以使用just安装PIL brew install pil。然后,您可能需要将安装目录($(brew --prefix)/lib/python2.7/site-packages)添加到PYTHONPATH中,或者将PIL目录本身的位置添加到PIL.pth任何site-packages目录中名为file的文件中,内容如下:

/usr/local/lib/python2.7/site-packages/PIL

(假设brew --prefix/usr/local)。

另外,您也可以从源代码下载/构建/安装它:

# download
curl -O -L http://effbot.org/media/downloads/Imaging-1.1.7.tar.gz
# extract
tar -xzf Imaging-1.1.7.tar.gz
cd Imaging-1.1.7
# build and install
python setup.py build
sudo python setup.py install
# or install it for just you without requiring admin permissions:
# python setup.py install --user

我刚刚(在OSX 10.7.2,XCode 4.2.1和System Python 2.7.1上)运行了上面的代码,尽管在我的环境中某些内容可能不是默认值,但它的构建还不错。

[homebrew]:http : //mxcl.github.com/homebrew/ “ Homebrew”

I take it you’re on Mac. See How can I install PIL on mac os x 10.7.2 Lion

If you use [homebrew][], you can install the PIL with just brew install pil. You may then need to add the install directory ($(brew --prefix)/lib/python2.7/site-packages) to your PYTHONPATH, or add the location of PIL directory itself in a file called PIL.pth file in any of your site-packages directories, with the contents:

/usr/local/lib/python2.7/site-packages/PIL

(assuming brew --prefix is /usr/local).

Alternatively, you can just download/build/install it from source:

# download
curl -O -L http://effbot.org/media/downloads/Imaging-1.1.7.tar.gz
# extract
tar -xzf Imaging-1.1.7.tar.gz
cd Imaging-1.1.7
# build and install
python setup.py build
sudo python setup.py install
# or install it for just you without requiring admin permissions:
# python setup.py install --user

I ran the above just now (on OSX 10.7.2, with XCode 4.2.1 and System Python 2.7.1) and it built just fine, though there is a possibility that something in my environment is non-default.

[homebrew]: http://mxcl.github.com/homebrew/ “Homebrew”


回答 8

如今,每个人都在PIL上使用友好的PIL叉子Pillow。

代替: sudo pip install pil

做: sudo pip install pillow

$ sudo apt-get install python-imaging
$ sudo -H pip install pillow

These days, everyone uses Pillow, a friendly PIL fork, over PIL.

Instead of: sudo pip install pil

Do: sudo pip install pillow

$ sudo apt-get install python-imaging
$ sudo -H pip install pillow

回答 9

对于Ubuntu,PIL不再起作用。我总是得到:

找不到与PIL匹配的分布

因此,安装python-imaging:

sudo apt-get install python-imaging

For Ubuntu, PIL is not working any more. I always get:

No matching distribution found for PIL

So install python-imaging:

sudo apt-get install python-imaging

回答 10

我遇到了同样的问题,但是通过安装 python-dev

在安装PIL之前,请运行以下命令:

sudo apt-get install python-dev

然后安装PIL:

pip install PIL

I’m having the same problem, but it gets solved with installation of python-dev.

Before installing PIL, run following command:

sudo apt-get install python-dev

Then install PIL:

pip install PIL

回答 11

安装过程中出现了一些错误。以防万一有人也有这个。尽管我已经是管理员用户,但不是root用户。

File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs
    mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/PIL'

Storing debug log for failure in /Users/wzbozon/Library/Logs/pip.log

添加“ sudo”解决了问题,使用sudo可以解决问题:

~/Documents/mv-server: $ sudo pip install Pillow

I had some errors during installation. Just in case somebody has this too. Despite that I already was sitting under admin user, but not root.

File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs
    mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/PIL'

Storing debug log for failure in /Users/wzbozon/Library/Logs/pip.log

Adding “sudo” solved the problem, with sudo it worked:

~/Documents/mv-server: $ sudo pip install Pillow

回答 12

对于CentOS:

yum install python-imaging

For CentOS:

yum install python-imaging

回答 13

我尝试了所有答案,但失败了。直接从官方站点获取源代码,然后构建安装成功。

  1. 前往网站 http://www.pythonware.com/products/pil/#pil117
  2. 单击“ Python Imaging Library 1.1.7源工具包”以下载源
  3. tar xf Imaging-1.1.7.tar.gz
  4. cd Imaging-1.1.7
  5. sudo python setup.py install

I tried all the answers, but failed. Directly get the source from the official site and then build install success.

  1. Go to the site http://www.pythonware.com/products/pil/#pil117
  2. Click “Python Imaging Library 1.1.7 Source Kit” to download the source
  3. tar xf Imaging-1.1.7.tar.gz
  4. cd Imaging-1.1.7
  5. sudo python setup.py install

回答 14

我用 sudo port install py27-Pillow

I nailed it by using sudo port install py27-Pillow


回答 15

尝试这个:

sudo pip install PIL --allow-external PIL --allow-unverified PIL

Try this:

sudo pip install PIL --allow-external PIL --allow-unverified PIL

回答 16

(窗口)如果Pilow不起作用,请尝试从http://www.pythonware.com/products/pil/下载pil

(Window) If Pilow not work try download pil at http://www.pythonware.com/products/pil/


回答 17

  • 首先,您应该运行此程序sudo apt-get build-dep python-imaging,它将为您提供可能需要的所有依赖项

  • 然后跑 sudo apt-get update && sudo apt-get -y upgrade

  • 其次是 sudo apt-get install python-pip

  • 然后最后安装Pil pip install pillow

  • First you should run this sudo apt-get build-dep python-imaging which will give you all the dependencies that you might need

  • Then run sudo apt-get update && sudo apt-get -y upgrade

  • Followed by sudo apt-get install python-pip

  • And then finally install Pil pip install pillow


回答 18

使用之前,请先搜索软件包管理器pip。在Arch Linux上,您可以通过以下方式获取PIL:pacman -S python2-pillow

Search on package manager before using pip. On Arch linux you can get PIL by pacman -S python2-pillow


回答 19

还有另一个名为的Python打包工具conda。当某些库需要安装C ++和其他非纯Python的绑定时,Conda优于pip(我认为)。Conda的安装中还包括点子,因此您仍然可以使用点子,但您也可以从conda中受益。

默认情况下,Conda还安装IPython,pil和许多其他库。我想你会喜欢的。

There’s another Python package tool called conda. Conda is preferred (I believe) over pip when there are libraries that need to install C++ and other bindings that aren’t pure Python. Conda includes pip in its installation as well so you can still use pip, but you also get the benefits of conda.

Conda also installs IPython, pil, and many other libraries by default. I think you’ll like it.


如何找到我的Python site-packages目录的位置?

问题:如何找到我的Python site-packages目录的位置?

我如何找到我的site-packages目录的位置?

How do I find the location of my site-packages directory?


回答 0

网站包目录有两种类型,全局目录和每个用户目录。

  1. 运行时会列出全局站点软件包(“ dist-packages ”)目录sys.path

    python -m site

    要在Python代码中getsitepackages站点模块运行更简洁的列表,请执行以下操作:

    python -c 'import site; print(site.getsitepackages())'

    注意:使用virtualenvs时,getsitepackages不可用,但是sys.path从上面将正确列出virtualenv的site-packages目录。在Python 3中,您可以改为使用sysconfig模块

    python3 -c 'import sysconfig; print(sysconfig.get_paths()["purelib"])'
  2. 每个用户站点包目录(PEP 370)是其中的Python安装本地套餐:

    python -m site --user-site

    如果这指向一个不存在的目录,请检查Python的退出状态并查看python -m site --help说明。

    提示:运行pip list --userpip freeze --user为您提供每个用户站点软件包的所有已安装列表。


实用技巧

  • <package>.__path__可让您识别特定包装的位置:(详细信息

    $ python -c "import setuptools as _; print(_.__path__)"
    ['/usr/lib/python2.7/dist-packages/setuptools']
    
  • <module>.__file__让您识别特定模块的位置:(差异

    $ python3 -c "import os as _; print(_.__file__)"
    /usr/lib/python3.6/os.py
    
  • 运行pip show <package>以显示Debian风格的软件包信息:

    $ pip show pytest
    Name: pytest
    Version: 3.8.2
    Summary: pytest: simple powerful testing with Python
    Home-page: https://docs.pytest.org/en/latest/
    Author: Holger Krekel, Bruno Oliveira, Ronny Pfannschmidt, Floris Bruynooghe, Brianna Laugher, Florian Bruhin and others
    Author-email: None
    License: MIT license
    Location: /home/peter/.local/lib/python3.4/site-packages
    Requires: more-itertools, atomicwrites, setuptools, attrs, pathlib2, six, py, pluggy
    

There are two types of site-packages directories, global and per user.

  1. Global site-packages (“dist-packages“) directories are listed in sys.path when you run:

    python -m site
    

    For a more concise list run getsitepackages from the site module in Python code:

    python -c 'import site; print(site.getsitepackages())'
    

    Note: With virtualenvs getsitepackages is not available, sys.path from above will list the virtualenv’s site-packages directory correctly, though. In Python 3, you may use the sysconfig module instead:

    python3 -c 'import sysconfig; print(sysconfig.get_paths()["purelib"])'
    
  2. The per user site-packages directory (PEP 370) is where Python installs your local packages:

    python -m site --user-site
    

    If this points to a non-existing directory check the exit status of Python and see python -m site --help for explanations.

    Hint: Running pip list --user or pip freeze --user gives you a list of all installed per user site-packages.


Practical Tips

  • <package>.__path__ lets you identify the location(s) of a specific package: (details)

    $ python -c "import setuptools as _; print(_.__path__)"
    ['/usr/lib/python2.7/dist-packages/setuptools']
    
  • <module>.__file__ lets you identify the location of a specific module: (difference)

    $ python3 -c "import os as _; print(_.__file__)"
    /usr/lib/python3.6/os.py
    
  • Run pip show <package> to show Debian-style package information:

    $ pip show pytest
    Name: pytest
    Version: 3.8.2
    Summary: pytest: simple powerful testing with Python
    Home-page: https://docs.pytest.org/en/latest/
    Author: Holger Krekel, Bruno Oliveira, Ronny Pfannschmidt, Floris Bruynooghe, Brianna Laugher, Florian Bruhin and others
    Author-email: None
    License: MIT license
    Location: /home/peter/.local/lib/python3.4/site-packages
    Requires: more-itertools, atomicwrites, setuptools, attrs, pathlib2, six, py, pluggy
    

回答 1

>>> import site; site.getsitepackages()
['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']

(或仅带的第一项site.getsitepackages()[0]

>>> import site; site.getsitepackages()
['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']

(or just first item with site.getsitepackages()[0])


回答 2

解决方案:

  • 在virtualenv外部-提供全局站点程序包的路径,
  • 包含virtualenv-提供virtualenv的站点包

…是单线的:

python -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())"

出于可读性考虑而格式化(而不是单行使用),其外观如下所示:

from distutils.sysconfig import get_python_lib
print(get_python_lib())


资料来源:“如何安装Django”文档的非常旧的版本(尽管这不仅对Django安装有用)

A solution that:

  • outside of virtualenv – provides the path of global site-packages,
  • insidue a virtualenv – provides the virtualenv’s site-packages

…is this one-liner:

python -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())"

Formatted for readability (rather than use as a one-liner), that looks like the following:

from distutils.sysconfig import get_python_lib
print(get_python_lib())


Source: an very old version of “How to Install Django” documentation (though this is useful to more than just Django installation)


回答 3

对于Ubuntu

python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"

…是不正确的。

它将指向您 /usr/lib/pythonX.X/dist-packages

该文件夹仅包含您的操作系统已自动安装的程序运行包。

在ubuntu上,包含通过setup_tools \ easy_install \ pip安装的软件包的site-packages文件夹位于/usr/local/lib/pythonX.X/dist-packages

如果用例与安装或阅读源代码有关,则第二个文件夹可能更有用。

如果您不使用Ubuntu,则可以安全地将第一个代码框复制粘贴到终端中。

For Ubuntu,

python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"

…is not correct.

It will point you to /usr/lib/pythonX.X/dist-packages

This folder only contains packages your operating system has automatically installed for programs to run.

On ubuntu, the site-packages folder that contains packages installed via setup_tools\easy_install\pip will be in /usr/local/lib/pythonX.X/dist-packages

The second folder is probably the more useful one if the use case is related to installation or reading source code.

If you do not use Ubuntu, you are probably safe copy-pasting the first code box into the terminal.


回答 4

这对我有用:

python -m site --user-site

This is what worked for me:

python -m site --user-site

回答 5

假设您已经安装了“ django”软件包。导入并输入dir(django)。它将向您显示该模块的所有功能和属性。键入python解释器-

>>> import django
>>> dir(django)
['VERSION', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'get_version']
>>> print django.__path__
['/Library/Python/2.6/site-packages/django']

如果您已经安装了Mercurial,则可以执行相同的操作。

这是给雪豹的。但我认为它通常也应该起作用。

Let’s say you have installed the package ‘django’. import it and type in dir(django). It will show you, all the functions and attributes with that module. Type in the python interpreter –

>>> import django
>>> dir(django)
['VERSION', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'get_version']
>>> print django.__path__
['/Library/Python/2.6/site-packages/django']

You can do the same thing if you have installed mercurial.

This is for Snow Leopard. But I think it should work in general as well.


回答 6

如其他人所述,distutils.sysconfig具有相关设置:

import distutils.sysconfig
print distutils.sysconfig.get_python_lib()

…尽管默认值的site.py含义有些粗略,如下所述:

import sys, os
print os.sep.join([sys.prefix, 'lib', 'python' + sys.version[:3], 'site-packages'])

(如果该常量不同,它还会添加${sys.prefix}/lib/site-python和添加两条路径sys.exec_prefix)。

也就是说,背景是什么?您不应该site-packages直接与自己混为一谈。setuptools / distutils将可以进行安装,并且您的程序可能在virtualenv中运行,其中pythonpath完全是用户本地的,因此也不应假定直接使用系统站点包。

As others have noted, distutils.sysconfig has the relevant settings:

import distutils.sysconfig
print distutils.sysconfig.get_python_lib()

…though the default site.py does something a bit more crude, paraphrased below:

import sys, os
print os.sep.join([sys.prefix, 'lib', 'python' + sys.version[:3], 'site-packages'])

(it also adds ${sys.prefix}/lib/site-python and adds both paths for sys.exec_prefix as well, should that constant be different).

That said, what’s the context? You shouldn’t be messing with your site-packages directly; setuptools/distutils will work for installation, and your program may be running in a virtualenv where your pythonpath is completely user-local, so it shouldn’t assume use of the system site-packages directly either.


回答 7

现代的stdlib方法是使用sysconfig模块,该模块在2.7和3.2+版本中可用。

sysconfig)不与混淆distutils.sysconfig子模块(在其他几个答案这里提到)。后者是一个完全不同的模块,缺少get_paths下面讨论的功能。

Python当前使用八个路径(docs):

  • stdlib:包含非平台特定标准Python库文件的目录。
  • platstdlib:包含特定于平台的标准Python库文件的目录。
  • platlib:特定于站点,特定于平台的文件的目录。
  • purelib:特定于站点的,非特定于平台的文件的目录。
  • include:非平台特定头文件的目录。
  • platinclude:特定于平台的头文件的目录。
  • scripts:脚本文件的目录。
  • data:数据文件目录。

在大多数情况下,发现此问题的用户会对“ purelib”路径感兴趣(在某些情况下,您可能也对“ platlib”感兴趣)。与当前接受的答案不同,无论您是否激活了virtualenv,该方法仍然有效。

在系统级别(在Mac OS上为Python 3.7.0):

>>> import sysconfig
>>> sysconfig.get_paths()['purelib']
'/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages'

有了静脉,你会得到这样的东西

>>> import sysconfig
>>> sysconfig.get_paths()['purelib']
'/private/tmp/.venv/lib/python3.7/site-packages'

还可以使用Shell脚本来显示这些详细信息,您可以通过将其sysconfig作为模块执行来调用这些详细信息:

python -m sysconfig

A modern stdlib way is using sysconfig module, available in version 2.7 and 3.2+.

Note: sysconfig (source) is not to be confused with the distutils.sysconfig submodule (source) mentioned in several other answers here. The latter is an entirely different module and it’s lacking the get_paths function discussed below.

Python currently uses eight paths (docs):

  • stdlib: directory containing the standard Python library files that are not platform-specific.
  • platstdlib: directory containing the standard Python library files that are platform-specific.
  • platlib: directory for site-specific, platform-specific files.
  • purelib: directory for site-specific, non-platform-specific files.
  • include: directory for non-platform-specific header files.
  • platinclude: directory for platform-specific header files.
  • scripts: directory for script files.
  • data: directory for data files.

In most cases, users finding this question would be interested in the ‘purelib’ path (in some cases, you might be interested in ‘platlib’ too). Unlike the current accepted answer, this method still works regardless of whether or not you have a virtualenv activated.

At system level (this is Python 3.7.0 on mac OS):

>>> import sysconfig
>>> sysconfig.get_paths()['purelib']
'/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages'

With a venv, you’ll get something like this

>>> import sysconfig
>>> sysconfig.get_paths()['purelib']
'/private/tmp/.venv/lib/python3.7/site-packages'

A shell script is also available to display these details, which you can invoke by executing sysconfig as a module:

python -m sysconfig

回答 8

在基于Debian的系统中随python安装一起安装的本机系统软件包可以在以下位置找到:

/usr/lib/python2.7/dist-packages/

在OSX中- /Library/Python/2.7/site-packages

通过使用此小代码:

from distutils.sysconfig import get_python_lib
print get_python_lib()

但是,pip可以在以下位置找到通过安装的软件包列表:

/ usr / local / bin /

或者,只需编写以下命令即可列出python软件包所在的所有路径。

>>> import site; site.getsitepackages()
['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']

注意:位置可能会因您的操作系统而异,例如在OSX中

>>> import site; site.getsitepackages()
['/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/site-python', '/Library/Python/2.7/site-packages']

The native system packages installed with python installation in Debian based systems can be found at :

/usr/lib/python2.7/dist-packages/

In OSX – /Library/Python/2.7/site-packages

by using this small code :

from distutils.sysconfig import get_python_lib
print get_python_lib()

However, the list of packages installed via pip can be found at :

/usr/local/bin/

Or one can simply write the following command to list all paths where python packages are.

>>> import site; site.getsitepackages()
['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']

Note: the location might vary based on your OS, like in OSX

>>> import site; site.getsitepackages()
['/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/site-python', '/Library/Python/2.7/site-packages']

回答 9

所有答案(或:一遍又一遍重复的相同答案)都不够。您要做的是:

from setuptools.command.easy_install import easy_install
class easy_install_default(easy_install):
  """ class easy_install had problems with the fist parameter not being
      an instance of Distribution, even though it was. This is due to
      some import-related mess.
      """

  def __init__(self):
    from distutils.dist import Distribution
    dist = Distribution()
    self.distribution = dist
    self.initialize_options()
    self._dry_run = None
    self.verbose = dist.verbose
    self.force = None
    self.help = 0
    self.finalized = 0

e = easy_install_default()
import distutils.errors
try:
  e.finalize_options()
except distutils.errors.DistutilsError:
  pass

print e.install_dir

最后一行显示安装目录。可在Ubuntu上使用,而以上版本则不能。不要问我有关Windows或其他dists的问题,但是由于它与easy_install默认使用的目录完全相同,因此在easy_install工作的所有地方(所以,甚至是macs),它都可能是正确的。玩得开心。注意:原始代码中包含许多脏话。

All the answers (or: the same answer repeated over and over) are inadequate. What you want to do is this:

from setuptools.command.easy_install import easy_install
class easy_install_default(easy_install):
  """ class easy_install had problems with the fist parameter not being
      an instance of Distribution, even though it was. This is due to
      some import-related mess.
      """

  def __init__(self):
    from distutils.dist import Distribution
    dist = Distribution()
    self.distribution = dist
    self.initialize_options()
    self._dry_run = None
    self.verbose = dist.verbose
    self.force = None
    self.help = 0
    self.finalized = 0

e = easy_install_default()
import distutils.errors
try:
  e.finalize_options()
except distutils.errors.DistutilsError:
  pass

print e.install_dir

The final line shows you the installation dir. Works on Ubuntu, whereas the above ones don’t. Don’t ask me about windows or other dists, but since it’s the exact same dir that easy_install uses by default, it’s probably correct everywhere where easy_install works (so, everywhere, even macs). Have fun. Note: original code has many swearwords in it.


回答 10

旁注:distutils.sysconfig.get_python_lib()如果存在多个site-packages目录(如本文推荐),则建议的解决方案()不起作用。它只会返回主site-packages目录。

,我也没有更好的解决方案。Python似乎不跟踪站点软件包目录,而只是跟踪其中的软件包。

A side-note: The proposed solution (distutils.sysconfig.get_python_lib()) does not work when there is more than one site-packages directory (as recommended by this article). It will only return the main site-packages directory.

Alas, I have no better solution either. Python doesn’t seem to keep track of site-packages directories, just the packages within them.


回答 11

这对我有用。这将使您同时获得dist-packages和site-packages文件夹。如果该文件夹不在Python的路径上,则无论如何都不会给您带来什么好处。

import sys; 
print [f for f in sys.path if f.endswith('packages')]

输出(Ubuntu安装):

['/home/username/.local/lib/python2.7/site-packages',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages']

This works for me. It will get you both dist-packages and site-packages folders. If the folder is not on Python’s path, it won’t be doing you much good anyway.

import sys; 
print [f for f in sys.path if f.endswith('packages')]

Output (Ubuntu installation):

['/home/username/.local/lib/python2.7/site-packages',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages']

回答 12

由于它具有“低技术”性质,因此该方法适用于虚拟环境内外的所有发行版。os模块始终位于“ site-packages”的父目录中

import os; print(os.path.dirname(os.__file__) + '/site-packages')

要将目录更改为站点程序包目录,我使用以下别名(在* nix系统上):

alias cdsp='cd $(python -c "import os; print(os.path.dirname(os.__file__))"); cd site-packages'

This should work on all distributions in and out of virtual environment due to it’s “low-tech” nature. The os module always resides in the parent directory of ‘site-packages’

import os; print(os.path.dirname(os.__file__) + '/site-packages')

To change dir to the site-packages dir I use the following alias (on *nix systems):

alias cdsp='cd $(python -c "import os; print(os.path.dirname(os.__file__))"); cd site-packages'

回答 13

get_python_lib已经提到的功能的附加说明:在某些平台上,不同的目录用于平台特定的模块(例如:需要编译的模块)。如果传递plat_specific=True给该函数,则将获得针对特定平台的软件包的站点软件包。

An additional note to the get_python_lib function mentioned already: on some platforms different directories are used for platform specific modules (eg: modules that require compilation). If you pass plat_specific=True to the function you get the site packages for platform specific packages.


回答 14

from distutils.sysconfig import get_python_lib
print get_python_lib()
from distutils.sysconfig import get_python_lib
print get_python_lib()

回答 15

点子显示将提供有关软件包的所有详细信息:https : //pip.pypa.io/en/stable/reference/pip_show/ [点子显示] [1]

获取位置:

pip show <package_name>| grep Location

pip show will give all the details about a package: https://pip.pypa.io/en/stable/reference/pip_show/ [pip show][1]

To get the location:

pip show <package_name>| grep Location

回答 16

回答老问题。但是为此使用ipython。

pip install ipython
ipython 
import imaplib
imaplib?

这将给出有关imaplib软件包的以下输出-

Type:        module
String form: <module 'imaplib' from '/usr/lib/python2.7/imaplib.py'>
File:        /usr/lib/python2.7/imaplib.py
Docstring:  
IMAP4 client.

Based on RFC 2060.

Public class:           IMAP4
Public variable:        Debug
Public functions:       Internaldate2tuple
                        Int2AP
                        ParseFlags
                        Time2Internaldate

Answer to old question. But use ipython for this.

pip install ipython
ipython 
import imaplib
imaplib?

This will give the following output about imaplib package –

Type:        module
String form: <module 'imaplib' from '/usr/lib/python2.7/imaplib.py'>
File:        /usr/lib/python2.7/imaplib.py
Docstring:  
IMAP4 client.

Based on RFC 2060.

Public class:           IMAP4
Public variable:        Debug
Public functions:       Internaldate2tuple
                        Int2AP
                        ParseFlags
                        Time2Internaldate

回答 17

您应该尝试使用此命令来确定pip的安装位置

Python 2

pip show six | grep "Location:" | cut -d " " -f2

Python 3

pip3 show six | grep "Location:" | cut -d " " -f2

You should try this command to determine pip’s install location

Python 2

pip show six | grep "Location:" | cut -d " " -f2

Python 3

pip3 show six | grep "Location:" | cut -d " " -f2

回答 18

我必须为正在处理的项目做些不同的事情:找到相对于基本安装前缀的相对 site-packages目录。如果site-packages文件夹位于中/usr/lib/python2.7/site-packages,则需要该/lib/python2.7/site-packages部件。我有,事实上,遇到在那里系统site-packages/usr/lib64和公认的答案没有对这些系统的工作。

与作弊者的答案类似,我的解决方案深入探究了Distutils的精髓,以发现实际上在内部传递的路径setup.py。弄清楚这真是太痛苦了,我不想让任何人不得不再次弄清楚这一点。

import sys
import os
from distutils.command.install import INSTALL_SCHEMES

if os.name == 'nt':
    scheme_key = 'nt'
else:
    scheme_key = 'unix_prefix'

print(INSTALL_SCHEMES[scheme_key]['purelib'].replace('$py_version_short', (str.split(sys.version))[0][0:3]).replace('$base', ''))

那应该打印类似/Lib/site-packages或的内容/lib/python3.6/site-packages

I had to do something slightly different for a project I was working on: find the relative site-packages directory relative to the base install prefix. If the site-packages folder was in /usr/lib/python2.7/site-packages, I wanted the /lib/python2.7/site-packages part. I have, in fact, encountered systems where site-packages was in /usr/lib64, and the accepted answer did NOT work on those systems.

Similar to cheater’s answer, my solution peeks deep into the guts of Distutils, to find the path that actually gets passed around inside setup.py. It was such a pain to figure out that I don’t want anyone to ever have to figure this out again.

import sys
import os
from distutils.command.install import INSTALL_SCHEMES

if os.name == 'nt':
    scheme_key = 'nt'
else:
    scheme_key = 'unix_prefix'

print(INSTALL_SCHEMES[scheme_key]['purelib'].replace('$py_version_short', (str.split(sys.version))[0][0:3]).replace('$base', ''))

That should print something like /Lib/site-packages or /lib/python3.6/site-packages.


回答 19

如果已将其添加到中,则PYTHONPATH还可以执行类似操作

import sys
print('\n'.join(sys.path))

If it is already added to the PYTHONPATH you can also do something like

import sys
print('\n'.join(sys.path))