标签归档:macos

为什么apt-get功能在Mac OS X v10.9(Mavericks)的终端中不起作用?

问题:为什么apt-get功能在Mac OS X v10.9(Mavericks)的终端中不起作用?

我正在观看此视频,如您所见,告诉我的第一个命令是:

sudo apt-get install python-setuptools

当我这样做时,它输出:

sudo: apt-get: command not found

我不知道为什么会这样。

如何解决此问题,以便正确遵循本教程?

I was watching this, and, as you can see, the first command I am told to put in is:

sudo apt-get install python-setuptools

When I do this, it outputs:

sudo: apt-get: command not found

I have no idea why this is the case.

How can I resolve this so I am following the tutorial correctly?


回答 0

Mac OS X没有apt-get。有一个叫做Homebrew的程序包管理器代替了。

该命令将是:

brew安装python

使用Homebrew安装否则会用到的软件包apt-get

我链接到的页面具有安装Homebrew的最新方法,但是目前,您可以按以下方式安装Homebrew:

在Mac OS X终端中键入以下内容:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

在那之后,Homebrew的用法为brew install <package>

XCode命令行工具是Homebrew的前提条件之一。

  1. 从App Store安装XCode。
  2. 请按照此Stack Overflow答案中的说明安装XCode命令行工具

背景

软件包管理器(如apt-getbrew)只是为您的系统提供了一种简单且自动化的安装软件包或库的方法。不同的系统使用不同的程序。 apt及其派生类在基于Debian的linux系统上使用。使用Red Hat式的Linux系统rpm(或者至少在很多年前,他们做了很多)。 yum还是基于RedHat的系统的软件包管理器。

基于高山的系统使用apk

警告

自2016年4月25日起,默认情况下自制软件会选择让用户加入分析。可以通过两种方式选择退出:

设置环境变量:

  1. 打开您喜欢的环境变量编辑器
  2. 进行以下设置:HOMEBREW_NO_ANALYTICS=1 在保存环境变量的任何地方(通常是~/.bash_profile
  3. 关闭文件,然后重新启动终端或source ~/.bash_profile

运行以下命令:

brew analytics off

然后可以使用以下命令检查分析状态:

brew analytics

Mac OS X doesn’t have apt-get. There is a package manager called Homebrew that is used instead.

This command would be:

brew install python

Use Homebrew to install packages that you would otherwise use apt-get for.

The page I linked to has an up-to-date way of installing homebrew, but at present, you can install Homebrew as follows:

Type the following in your Mac OS X terminal:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

After that, usage of Homebrew is brew install <package>.

One of the prerequisites for Homebrew are the XCode command line tools.

  1. Install XCode from the App Store.
  2. Follow the directions in this Stack Overflow answer to install the XCode Command Line Tools.

Background

A package manager (like apt-get or brew) just gives your system an easy and automated way to install packages or libraries. Different systems use different programs. apt and its derivatives are used on Debian based linux systems. Red Hat-ish Linux systems use rpm (or at least they did many, many, years ago). yum is also a package manager for RedHat based systems.

Alpine based systems use apk.

Warning

As of 25 April 2016, homebrew opts the user in to sending analytics by default. This can be opted out of in two ways:

Setting an environment variable:

  1. Open your favorite environment variable editor.
  2. Set the following: HOMEBREW_NO_ANALYTICS=1 in whereever you keep your environment variables (typically something like ~/.bash_profile)
  3. Close the file, and either restart the terminal or source ~/.bash_profile.

Running the following command:

brew analytics off

the analytics status can then be checked with the command:

brew analytics

回答 1

因为Homebrew是我在macOS上的最爱,尽管有可能apt-get使用Fink在macOS上使用。

As Homebrew is my favorite for macOS although it is possible to have apt-get on macOS using Fink.


回答 2

MacPorts是OS X的另一个软件包管理器:。

安装说明在该MacPorts的项目-下载和安装之后,一个问题sudo port install pythonXX,这里XX2735

MacPorts is another package manager for OS X:.

Installation instructions are at The MacPorts Project — Download & Installation after which one issues sudo port install pythonXX, where XX is 27 or 35.


回答 3

Conda也可以用作程序包管理器。可以从Anaconda安装。

另外,一个免费的最小安装程序是Miniconda

Conda can also be used as package manager. It can be installed from Anaconda.

Alternatively, a free minimal installer is Miniconda.


回答 4

您还可以使用curl命令安装东西,只要在URL提及apt-get的地方…

例如,

curl -O http://www.magentocommerce.com/downloads/assets/1.8.1.0/magento-1.8.1.0.tar.gz

Alternatively You can use the brew or curl command for installing things, wherever apt-get is mentioned with a URL…

For example,

curl -O http://www.magentocommerce.com/downloads/assets/1.8.1.0/magento-1.8.1.0.tar.gz

您如何在交互式Python中查看整个命令历史记录?

问题:您如何在交互式Python中查看整个命令历史记录?

我正在Mac OS X上使用默认的python解释器,并且Cmd+ K(清除了)我以前的命令。我可以使用箭头键逐一浏览它们。但是bash shell中是否有–history选项之类的选项,可以显示您到目前为止输入的所有命令?

I’m working on the default python interpreter on Mac OS X, and I Cmd+K (cleared) my earlier commands. I can go through them one by one using the arrow keys. But is there an option like the –history option in bash shell, which shows you all the commands you’ve entered so far?


回答 0

使用readline.get_current_history_length()获得的长度,并readline.get_history_item()查看每个。


回答 1

用于打印整个历史记录的代码:

Python 3

单线(快速复制和粘贴):

import readline; print('\n'.join([str(readline.get_history_item(i + 1)) for i in range(readline.get_current_history_length())]))

(或更长的版本…)

import readline
for i in range(readline.get_current_history_length()):
    print (readline.get_history_item(i + 1))

Python 2

单线(快速复制和粘贴):

import readline; print '\n'.join([str(readline.get_history_item(i + 1)) for i in range(readline.get_current_history_length())])

(或更长的版本…)

import readline
for i in range(readline.get_current_history_length()):
    print readline.get_history_item(i + 1)

注意get_history_item()索引从1到n。

Code for printing the entire history:

Python 3

One-liner (quick copy and paste):

import readline; print('\n'.join([str(readline.get_history_item(i + 1)) for i in range(readline.get_current_history_length())]))

(Or longer version…)

import readline
for i in range(readline.get_current_history_length()):
    print (readline.get_history_item(i + 1))

Python 2

One-liner (quick copy and paste):

import readline; print '\n'.join([str(readline.get_history_item(i + 1)) for i in range(readline.get_current_history_length())])

(Or longer version…)

import readline
for i in range(readline.get_current_history_length()):
    print readline.get_history_item(i + 1)

Note: get_history_item() is indexed from 1 to n.


回答 2

使用python 3解释器将历史记录写入
~/.python_history

With python 3 interpreter the history is written to
~/.python_history


回答 3

如果要将历史记录写入文件:

import readline
readline.write_history_file('python_history.txt')

帮助功能提供:

Help on built-in function write_history_file in module readline:

write_history_file(...)
    write_history_file([filename]) -> None
    Save a readline history file.
    The default filename is ~/.history.

If you want to write the history to a file:

import readline
readline.write_history_file('python_history.txt')

The help function gives:

Help on built-in function write_history_file in module readline:

write_history_file(...)
    write_history_file([filename]) -> None
    Save a readline history file.
    The default filename is ~/.history.

回答 4

由于以上内容仅适用于python 2.x,而python 3.x(特别是3.5)则类似,但略有修改:

import readline
for i in range(readline.get_current_history_length()):
    print (readline.get_history_item(i + 1))

注意额外的()

(使用shell脚本解析.python_history或使用python修改以上代码是个人喜好和情况的问题恕我直言)

Since the above only works for python 2.x for python 3.x (specifically 3.5) is similar but with a slight modification:

import readline
for i in range(readline.get_current_history_length()):
    print (readline.get_history_item(i + 1))

note the extra ()

(using shell scripts to parse .python_history or using python to modify the above code is a matter of personal taste and situation imho)


回答 5

在IPython中,%history -g应该为您提供完整的命令历史记录。默认配置还将您的历史记录保存到用户目录中名为.python_history的文件中。

In IPython %history -g should give you the entire command history. The default configuration also saves your history into a file named .python_history in your user directory.


回答 6

一个简单的函数来获取类似于unix / bash版本的历史记录。

希望它对一些新人有所帮助。

def ipyhistory(lastn=None):
    """
    param: lastn Defaults to None i.e full history. If specified then returns lastn records from history.
           Also takes -ve sequence for first n history records.
    """
    import readline
    assert lastn is None or isinstance(lastn, int), "Only integers are allowed."
    hlen = readline.get_current_history_length()
    is_neg = lastn is not None and lastn < 0
    if not is_neg:
        flen = len(str(hlen)) if not lastn else len(str(lastn))
        for r in range(1,hlen+1) if not lastn else range(1, hlen+1)[-lastn:]:
            print(": ".join([str(r if not lastn else r + lastn - hlen ).rjust(flen), readline.get_history_item(r)]))
    else:
        flen = len(str(-hlen))
        for r in range(1, -lastn + 1):
            print(": ".join([str(r).rjust(flen), readline.get_history_item(r)]))

片段:经过Python3测试。让我知道python2是否有故障。样品:

完整历史记录: ipyhistory()

最近的10个历史记录: ipyhistory(10)

前10个历史记录: ipyhistory(-10)

希望它能帮助小伙子们。

A simple function to get the history similar to unix/bash version.

Hope it helps some new folks.

def ipyhistory(lastn=None):
    """
    param: lastn Defaults to None i.e full history. If specified then returns lastn records from history.
           Also takes -ve sequence for first n history records.
    """
    import readline
    assert lastn is None or isinstance(lastn, int), "Only integers are allowed."
    hlen = readline.get_current_history_length()
    is_neg = lastn is not None and lastn < 0
    if not is_neg:
        flen = len(str(hlen)) if not lastn else len(str(lastn))
        for r in range(1,hlen+1) if not lastn else range(1, hlen+1)[-lastn:]:
            print(": ".join([str(r if not lastn else r + lastn - hlen ).rjust(flen), readline.get_history_item(r)]))
    else:
        flen = len(str(-hlen))
        for r in range(1, -lastn + 1):
            print(": ".join([str(r).rjust(flen), readline.get_history_item(r)]))

Snippet: Tested with Python3. Let me know if there are any glitches with python2. Samples:

Full History : ipyhistory()

Last 10 History: ipyhistory(10)

First 10 History: ipyhistory(-10)

Hope it helps fellas.


回答 7

@ Jason-V,真的有帮助,谢谢。然后,我找到了这些示例,并编写了自己的代码段。

#!/usr/bin/env python3
import os, readline, atexit
python_history = os.path.join(os.environ['HOME'], '.python_history')
try:
  readline.read_history_file(python_history)
  readline.parse_and_bind("tab: complete")
  readline.set_history_length(5000)
  atexit.register(readline.write_history_file, python_history)
except IOError:
  pass
del os, python_history, readline, atexit 

@Jason-V, it really help, thanks. then, i found this examples and composed to own snippet.

#!/usr/bin/env python3
import os, readline, atexit
python_history = os.path.join(os.environ['HOME'], '.python_history')
try:
  readline.read_history_file(python_history)
  readline.parse_and_bind("tab: complete")
  readline.set_history_length(5000)
  atexit.register(readline.write_history_file, python_history)
except IOError:
  pass
del os, python_history, readline, atexit 

回答 8

这应该给您单独打印出的命令:

import readline
map(lambda p:print(readline.get_history_item(p)),
    map(lambda p:p, range(readline.get_current_history_length()))
)

This should give you the commands printed out in separate lines:

import readline
map(lambda p:print(readline.get_history_item(p)),
    map(lambda p:p, range(readline.get_current_history_length()))
)

回答 9

重排Doogle的答案,该答案不打印行号,但允许指定要打印的行数。

def history(lastn=None):
    """
    param: lastn Defaults to None i.e full history. If specified then returns lastn records from history.
           Also takes -ve sequence for first n history records.
    """
    import readline
    assert lastn is None or isinstance(lastn, int), "Only integers are allowed."
    hlen = readline.get_current_history_length()
    is_neg = lastn is not None and lastn < 0
    if not is_neg:
        for r in range(1,hlen+1) if not lastn else range(1, hlen+1)[-lastn:]:
            print(readline.get_history_item(r))
    else:
        for r in range(1, -lastn + 1):
            print(readline.get_history_item(r))

Rehash of Doogle‘s answer that doesn’t printline numbers, but does allow specifying the number of lines to print.

def history(lastn=None):
    """
    param: lastn Defaults to None i.e full history. If specified then returns lastn records from history.
           Also takes -ve sequence for first n history records.
    """
    import readline
    assert lastn is None or isinstance(lastn, int), "Only integers are allowed."
    hlen = readline.get_current_history_length()
    is_neg = lastn is not None and lastn < 0
    if not is_neg:
        for r in range(1,hlen+1) if not lastn else range(1, hlen+1)[-lastn:]:
            print(readline.get_history_item(r))
    else:
        for r in range(1, -lastn + 1):
            print(readline.get_history_item(r))

socket.error:[Errno 48]地址已在使用中

问题:socket.error:[Errno 48]地址已在使用中

我正在尝试从Mac终端使用python设置服务器。

我导航到文件夹位置的一种用法:

python -m SimpleHTTPServer

但这给了我错误:

socket.error: [Errno 48] Address already in use

之前,我曾使用同一命令为计算机中不同位置的其他网站打开连接。

I’m trying to set up a server with python from mac terminal.

I navigate to folder location an use:

python -m SimpleHTTPServer

But this gives me error:

socket.error: [Errno 48] Address already in use

I had previously open a connection using the same command for a different website in a different location in my machine.


回答 0

您已经有一个绑定到默认端口(8000)的进程。如果您之前已经运行过相同的模块,则很可能该进程仍绑定到端口。首先尝试找到其他过程:

$ ps -fA | grep python
  501 81651 12648   0  9:53PM ttys000    0:00.16 python -m SimpleHTTPServer

包含命令参数,因此,SimpleHTTPServer如果有多个python进程处于活动状态,则可以发现其中一个正在运行。您可能想测试是否http://localhost:8000/仍然显示本地文件的目录列表。

第二个数字是进程号;通过发送信号来停止服务器:

kill 81651

这发送一个标准SIGTERM信号;如果该过程没有响应,则您可能不得不采用更严格的方法,例如发送SIGKILLkill -s KILL <pid>kill -9 <pid>)信号。有关更多详细信息,请参见Wikipedia

可替代地,一个上运行服务器不同端口,通过指定在命令行上的备用端口:

$ python -m SimpleHTTPServer 8910
Serving HTTP on 0.0.0.0 port 8910 ...

然后以方式访问服务器http://localhost:8910; 如果8910尚未使用该端口,则可以是1024或更高版本中的任何数字。

You already have a process bound to the default port (8000). If you already ran the same module before, it is most likely that process still bound to the port. Try and locate the other process first:

$ ps -fA | grep python
  501 81651 12648   0  9:53PM ttys000    0:00.16 python -m SimpleHTTPServer

The command arguments are included, so you can spot the one running SimpleHTTPServer if more than one python process is active. You may want to test if http://localhost:8000/ still shows a directory listing for local files.

The second number is the process number; stop the server by sending it a signal:

kill 81651

This sends a standard SIGTERM signal; if the process is unresponsive you may have to resort to tougher methods like sending a SIGKILL (kill -s KILL <pid> or kill -9 <pid>) signal instead. See Wikipedia for more details.

Alternatively, run the server on a different port, by specifying the alternative port on the command line:

$ python -m SimpleHTTPServer 8910
Serving HTTP on 0.0.0.0 port 8910 ...

then access the server as http://localhost:8910; where 8910 can be any number from 1024 and up, provided the port is not already taken.


回答 1

简单的解决方案:

  1. 使用port查找过程8080

    sudo lsof -i:8080

  2. 杀死它:

    kill XXXX

Simple solution:

  1. Find the process using port 8080:
`sudo lsof -i:8080`
  1. Kill the process on that port:
`kill $PID`

PID is got from step 1’s output.


回答 2

 sudo lsof -i:5000

这将为您提供使用端口的进程列表(如果有)。给定进程列表后,使用PID列上的ID终止进程使用

 kill 379 #use the provided PID

Use

 sudo lsof -i:5000

This will give you a list of processes using the port if any. Once the list of processes is given, use the id on the PID column to terminate the process use

 kill 379 #use the provided PID

回答 3

顺便说一句,为防止发生这种情况,只需在SimpleHTTPServer仍正常运行时在终端中按Ctrl+ C。这将“正确地”停止服务器并释放端口,因此您不必在重新启动服务器之前再次查找并终止该进程。

(Mods:我确实尝试过将此评论放在它所属的最佳答案上,但是我没有足够的声誉。)

By the way, to prevent this from happening in the first place, simply press Ctrl+C in terminal while SimpleHTTPServer is still running normally. This will “properly” stop the server and release the port so you don’t have to find and kill the process again before restarting the server.

(Mods: I did try to put this comment on the best answer where it belongs, but I don’t have enough reputation.)


回答 4

简单的一行命令即可删除它,在终端中键入以下命令,

ps -a

这将列出所有进程,签出Python正在使用的结账,并在终端中键入bellow命令,

kill -9 (processID) 

例如杀死-9 33178

Simple one line command to get rid of it, type below command in terminal,

ps -a

This will list out all process, checkout which is being used by Python and type bellow command in terminal,

kill -9 (processID) 

For example kill -9 33178


回答 5

您也可以在第二高的可用端口上服务,在Python中执行以下操作:

import SimpleHTTPServer
import SocketServer

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler

port = 8000
while True:
    try:
        httpd = SocketServer.TCPServer(('', port), Handler)
        print 'Serving on port', port
        httpd.serve_forever()
    except SocketServer.socket.error as exc:
        if exc.args[0] != 48:
            raise
        print 'Port', port, 'already in use'
        port += 1
    else:
        break

如果您需要对其他实用程序执行相同的操作,则作为bash脚本可能会更方便:

#!/usr/bin/env bash

MIN_PORT=${1:-1025}
MAX_PORT=${2:-65535}

(netstat -atn | awk '{printf "%s\n%s\n", $4, $4}' | grep -oE '[0-9]*$'; seq "$MIN_PORT" "$MAX_PORT") | sort -R | head -n 1

将该名称设置为可执行文件,get-free-port您可以执行以下操作:

someprogram --port=$(get-free-port)

这不如原生Python方法可靠,因为bash脚本无法捕获端口-另一个进程可以在进程捕获端口之前捕获端口(竞赛条件)-但在使用不支持该功能的实用程序时仍然足够有用没有自己尝试的方法。

You can also serve on the next-highest available port doing something like this in Python:

import SimpleHTTPServer
import SocketServer

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler

port = 8000
while True:
    try:
        httpd = SocketServer.TCPServer(('', port), Handler)
        print 'Serving on port', port
        httpd.serve_forever()
    except SocketServer.socket.error as exc:
        if exc.args[0] != 48:
            raise
        print 'Port', port, 'already in use'
        port += 1
    else:
        break

If you need to do the same thing for other utilities, it may be more convenient as a bash script:

#!/usr/bin/env bash

MIN_PORT=${1:-1025}
MAX_PORT=${2:-65535}

(netstat -atn | awk '{printf "%s\n%s\n", $4, $4}' | grep -oE '[0-9]*$'; seq "$MIN_PORT" "$MAX_PORT") | sort -R | head -n 1

Set that up as a executable with the name get-free-port and you can do something like this:

someprogram --port=$(get-free-port)

That’s not as reliable as the native Python approach because the bash script doesn’t capture the port — another process could grab the port before your process does (race condition) — but still may be useful enough when using a utility that doesn’t have a try-try-again approach of its own.


回答 6

我是Python的新手,但是经过简短的研究,我发现这是典型的套接字绑定。碰巧的是,套接字仍在使用中,您可能必须等待使用它。或者,您可以添加:

tcpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

这将使端口在较短的时间内可用。就我而言,它几乎可以立即使端口可用。

I am new to Python, but after my brief research I found out that this is typical of sockets being binded. It just so happens that the socket is still being used and you may have to wait to use it. Or, you can just add:

tcpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

This should make the port available within a shorter time. In my case, it made the port available almost immediately.


回答 7

以防万一以上解决方案不起作用:

  1. 获取您的进程正在监听的端口:

    $ ps斧| grep python

  2. 杀死进程

    $杀死PROCESS_NAME

Just in case above solutions didn’t work:

  1. Get the port your process is listening to:

    $ ps ax | grep python

  2. Kill the Process

    $ kill PROCESS_NAME


回答 8

我有一个树莓派,并且正在使用python网络服务器(使用Flask)。我已经尝试了以上所有内容,唯一的解决方案是关闭terminal(shell),然后再次打开它。或重新启动树莓派,因为没有什么可以阻止该网络服务器…

I have a raspberry pi, and I am using python web server (using Flask). I have tried everything above, the only solution is to close the terminal(shell) and open it again. Or restart the raspberry pi, because nothing stops that webserver…


回答 9

您可以使用允许服务器重用地址allow_reuse_address

服务器是否允许重用地址。默认值为False,可以在子类中设置以更改策略。

import SimpleHTTPServer, SocketServer
PORT = 8000
httpd = SocketServer.TCPServer(("", PORT), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.allow_reuse_address = True
print "Serving at port", PORT
httpd.serve_forever()

You can allow the server to reuse an address with allow_reuse_address.

Whether the server will allow the reuse of an address. This defaults to False, and can be set in subclasses to change the policy.

import SimpleHTTPServer, SocketServer
PORT = 8000
httpd = SocketServer.TCPServer(("", PORT), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.allow_reuse_address = True
print "Serving at port", PORT
httpd.serve_forever()

找不到Virtualenv命令

问题:找不到Virtualenv命令

virtualenv尽管进行了种种尝试,我还是无法上班。我virtualenv使用以下命令安装在MAC OS X上:

pip install virtualenv

并已将新增PATH至我的.bash_profile。每当我尝试运行该virtualenv命令时,它都会返回:

-bash: virtualenv: command not found

每次运行pip install virtualenv,它都会返回:

Requirement already satisfied (use --upgrade to upgrade): virtualenv in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages

我了解在Mac中,virtualenv应正确安装

/usr/local/bin

virtualenv确实安装/usr/local/bin,但每当我试图运行virtualenv命令,该命令没有找到。我也尝试virtualenv在目录中运行命令/usr/local/bin,它给我相同的结果:

-bash: virtualenv: command not found

这些是我添加到.bash_profile中的路径

export PATH=$PATH:/usr/local/bin
export PATH=$PATH:/usr/local/bin/python
export PATH=$PATH:/Library/Framework/Python.framework/Version/2.7/lib/site-packages

有任何解决方法吗?为什么会这样呢?

I couldn’t get virtualenv to work despite various attempts. I installed virtualenv on MAC OS X using:

pip install virtualenv

and have also added the PATH into my .bash_profile. Every time I try to run the virtualenv command, it returns:

-bash: virtualenv: command not found

Every time I run pip install virtualenv, it returns:

Requirement already satisfied (use --upgrade to upgrade): virtualenv in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages

I understand that in mac, the virtualenv should be correctly installed in

/usr/local/bin

The virtualenv is indeed installed in /usr/local/bin, but whenever I try to run the virtualenv command, the command is not found. I’ve also tried to run the virtualenv command in the directory /usr/local/bin, and it gives me the same result:

-bash: virtualenv: command not found

These are the PATHs I added to my .bash_profile

export PATH=$PATH:/usr/local/bin
export PATH=$PATH:/usr/local/bin/python
export PATH=$PATH:/Library/Framework/Python.framework/Version/2.7/lib/site-packages

Any workarounds for this? Why is this the case?


回答 0

如果您使用

pip install virtualenv

你需要跑步

sudo /usr/bin/easy_install virtualenv

把它放进去/usr/local/bin/

上面的目录默认情况下应该在您的目录中PATH;否则,请相应地编辑您的.zshrc(或。bashrc)。

If you installed it with

pip install virtualenv

You need to run

sudo /usr/bin/easy_install virtualenv

which puts it in /usr/local/bin/.

The above directory by default should be in your PATH; otherwise, edit your .zshrc (or .bashrc) accordingly.


回答 1

我遇到了同样的问题,这就是我解决的方法:

  1. 这个问题发生在我身上,因为我是通过pip以普通用户(不是root)的身份安装virtualenv的。pip将软件包安装到目录中~/.local/lib/pythonX.X/site-packages
  2. 当我以root用户或具有管理员权限(sudo)运行pip时,它在中安装了软件包/usr/lib/pythonX.X/dist-packages。对于您来说,此路径可能有所不同。
  3. 只在第二种情况下才能识别virtualenv命令
  4. 因此,要解决此问题,请执行pip uninstall virtualenv然后重新安装sudo pip install virtualenv(或以root身份安装)

I faced the same issue and this is how I solved it:

  1. The issue occurred to me because I installed virtualenv via pip as a regular user (not root). pip installed the packages into the directory ~/.local/lib/pythonX.X/site-packages
  2. When I ran pip as root or with admin privileges (sudo), it installed packages in /usr/lib/pythonX.X/dist-packages. This path might be different for you.
  3. virtualenv command gets recognized only in the second scenario
  4. So, to solve the issue, do pip uninstall virtualenv and then reinstall it with sudo pip install virtualenv (or install as root)

回答 2

最简单的答案。只是:

pip uninstall virtualenv

然后:

pip install virtualenv

或者sudo,在这种情况下,您可能使用来安装了virtualenv :

pip install --user virtualenv

The simplest answer. Just:

pip uninstall virtualenv

and then:

pip install virtualenv

Or you maybe installed virtualenv with sudo, in that case:

pip install --user virtualenv

回答 3

在Ubuntu 18.04 LTS上,我也遇到了相同的错误。以下命令有效:

sudo apt-get install python-virtualenv

On Ubuntu 18.04 LTS I also faced same error. Following command worked:

sudo apt-get install python-virtualenv

回答 4

我在Mac OS X El Capitan上也遇到了同样的问题。

当我这样安装时virtualenvsudo pip3 install virtualenv我没有virtualenv在命令行下。

我按照以下步骤解决了这个问题:

  1. 卸载以前的安装。
  2. virtualenv安装前通过调用切换到超级用户帐户sudo su
  3. virtualenv通过调用安装pip3 install virtualenv
  4. 最后,您应该可以virtualenv同时从usersuper user帐户访问。

I had same problem on Mac OS X El Capitan.

When I installed virtualenv like that sudo pip3 install virtualenv I didn’t have virtualenv under my command line.

I solved this problem by following those steps:

  1. Uninstall previous installations.
  2. Switch to super user account prior to virtualenv installation by calling sudo su
  3. Install virtualenv by calling pip3 install virtualenv
  4. Finally you should be able to access virtualenv from both user and super user account.

回答 5

找出问题

尝试使用--verbose标志进行安装

pip install virtualenv --verbose

输出看起来像这样

  ..
  Using cached virtualenv-15.1.0-py2.py3-none-any.whl
  Downloading from URL https://pypi.python.org/packages/6f/86/3dc328ee7b1a6419ebfac7896d882fba83c48e3561d22ddddf38294d3e83/virtualenv-15.1.0-py2.py3-none-any.whl#md5=aa7e5b86cc8cdb99794c4b99e8d670f3 (from https://pypi.python.org/simple/virtualenv/)
Installing collected packages: virtualenv

  changing mode of /home/manos/.local/bin/virtualenv to 755
Successfully installed virtualenv-15.1.0
Cleaning up...

从输出中我们可以看到它已安装在,/home/manos/.local/bin/virtualenv因此我们确保PATH包含该文件。

echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

以我为例,我们可以清楚地看到它/home/manos/.local/bin完全丢失了,这就是为什么Shell无法找到程序的原因。

解决方案

我们可以通过多种方式解决此问题:

  1. 我们可以通过点子选项直接安装到特定目录(不推荐)。
  2. /usr/local/bin或类似位置创建适当的符号链接。
  3. 附加/home/manos/.local/bin到PATH。
  4. 以sudo的形式安装以直接安装到 /usr/local/bin

最后两个选项可能是最明智的。最后一个解决方案是最简单的,因此我将仅介绍解决方案3。

将此添加到〜/ .profile:

PATH="$PATH:$HOME/.local/bin"

注销并再次登录,它应该可以工作。

Figure out the problem

Try installing with the --verbose flag

pip install virtualenv --verbose

Output will look something like this

  ..
  Using cached virtualenv-15.1.0-py2.py3-none-any.whl
  Downloading from URL https://pypi.python.org/packages/6f/86/3dc328ee7b1a6419ebfac7896d882fba83c48e3561d22ddddf38294d3e83/virtualenv-15.1.0-py2.py3-none-any.whl#md5=aa7e5b86cc8cdb99794c4b99e8d670f3 (from https://pypi.python.org/simple/virtualenv/)
Installing collected packages: virtualenv

  changing mode of /home/manos/.local/bin/virtualenv to 755
Successfully installed virtualenv-15.1.0
Cleaning up...

From the output we can see that it’s installed at /home/manos/.local/bin/virtualenv so let’s ensure PATH includes that.

echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

In my case we can clearly see that /home/manos/.local/bin is totally missing and that’s why the shell can’t find the program.

Solutions

We can solve this in many ways:

  1. We can install directly to a specific directory by fiddling with pip options (not recomended).
  2. Create appropriate symlinks at /usr/local/bin or similar.
  3. Append /home/manos/.local/bin to PATH.
  4. Install as sudo to install directly to /usr/local/bin

The two last options are probably the most sensible. The last solution is the simplest so therefore I will just show solution 3.

Add this to ~/.profile:

PATH="$PATH:$HOME/.local/bin"

Logout out and in again and it should work.


回答 6

python3 -m virtualenv virtualenv_name

python -m virtualenv virtualenv_name

python3 -m virtualenv virtualenv_name

python -m virtualenv virtualenv_name


回答 7

就我而言,我跑来pip show virtualenv获取有关virtualenv软件包的信息。我将看起来与此相似,还将显示软件包的位置:

user@machine:~$ pip show virtualenv
Name: virtualenv
Version: 16.2.0
Summary: Virtual Python Environment builder
Home-page: https://virtualenv.pypa.io/
Author: Ian Bicking
Author-email: ianb@colorstudy.com
License: MIT
Location: /home/user/.local/lib/python3.6/site-packages
Requires: setuptools

从那个位置抓取到该位置的.local一部分,在这种情况下为/home/user/.local/。您可以在下找到virtualenv命令/home/user/.local/bin/virtualenv

然后,您可以运行命令/home/user/.local/bin/virtualenv newvirtualenv

In my case, I ran pip show virtualenv to get the information about virtualenv package. I will look similar to this and will also show location of the package:

user@machine:~$ pip show virtualenv
Name: virtualenv
Version: 16.2.0
Summary: Virtual Python Environment builder
Home-page: https://virtualenv.pypa.io/
Author: Ian Bicking
Author-email: ianb@colorstudy.com
License: MIT
Location: /home/user/.local/lib/python3.6/site-packages
Requires: setuptools

From that grab the part of location up to the .local part, which in this case is /home/user/.local/. You can find virtualenv command under /home/user/.local/bin/virtualenv.

You can then run commands like /home/user/.local/bin/virtualenv newvirtualenv.


回答 8

我遇到过同样的问题。我使用以下步骤使其工作

sudo pip uninstall virtualenv

sudo -H pip install virtualenv

这就对了。它开始工作了。

sudo -H—-> sudo -H:HOME变量设置为目标用户主目录的用法。

I had the same issue. I used the following steps to make it work

sudo pip uninstall virtualenv

sudo -H pip install virtualenv

That is it. It started working.

Usage of sudo -H—-> sudo -H: set HOME variable to target user’s home dir.


回答 9

您说过,每次运行pip install都会得到回报Requirement already satisfied (use --upgrade to upgrade): virtualenv in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages。您需要执行以下操作:

  1. 更改目录(转到其中virtualenv.py的目录) cd /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages
  2. 如果您执行了一个操作,ls您将看到脚本在那里virtualenv.py
  3. 像这样运行脚本: python virtualenv.py --distribute /the/path/at/which/you/want/the/new/venv/at theNameOfTheNewVirtualEnv

希望这可以帮助。我的建议是研究更多静脉。这是一个很好的资源:https : //www.dabapps.com/blog/introduction-to-pip-and-virtualenv-python/

You said that every time you run the pip install you get Requirement already satisfied (use --upgrade to upgrade): virtualenv in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages. What you need to do is the following:

  1. Change Directory (go to to the one where the virtualenv.py) cd /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages
  2. If you do an ls you will see that the script is there virtualenv.py
  3. Run the script like this: python virtualenv.py --distribute /the/path/at/which/you/want/the/new/venv/at theNameOfTheNewVirtualEnv

Hope this helps. My advice would be to research venvs more. Here is a good resource: https://www.dabapps.com/blog/introduction-to-pip-and-virtualenv-python/


回答 10

我遇到了麻烦,因为我习惯于安装python-virtualenv软件包。要使其正常工作,我必须使用删除该软件包apt-get remove python-virtualenv并使用进行安装pip install virtualenv

I had troubles because I used apt to install python-virtualenv package. To get it working I had to remove this package with apt-get remove python-virtualenv and install it with pip install virtualenv.


回答 11

确保该virtualenv可执行文件。

如果virtualenv未找到,/usr/local/bin/virtualenv则应运行完整路径()。

Ensure that virtualenv is executable.

If virtualenv is not found, running the full path (/usr/local/bin/virtualenv) should work.


回答 12

我认为可以使用简单的符号链接来解决您的问题,但是您正在创建指向错误文件的符号链接。据我所知virtualenv已安装到/Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenv,(您可以更改Python版本的数字),因此用于创建符号链接命令应为:

ln -s /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenv /usr/local/bin/virtualenv

I think your problem can be solved using a simple symbolic link, but you are creating the symbolic link to the wrong file. As far as I know virtualenv is installed to /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenv, (you can change the numbers for your Python version) so the command for creating the symbolic link should be:

ln -s /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenv /usr/local/bin/virtualenv

回答 13

在ubuntu 18.4上,使用pip的AWS安装无法正常工作。使用apt-get install为我解决了问题。

sudo apt-get install python-virtualenv

并检查

virtualenv --version

On ubuntu 18.4 on AWS installation with pip don’t work correctly. Using apt-get install the problem was solved for me.

sudo apt-get install python-virtualenv

and to check

virtualenv --version

回答 14

同样的问题: 所以,我只是做了pip uninstall virtualenv 那么 pip install virtualenv

pip install virtualenv --user

使用缓存的https://files.pythonhosted.org/packages/b6/30/96a02b2287098b23b875bc8c2f58071c35d2efe84f747b64d523721dc2b5/virtualenv-16.0.0-py2.py3-none-any.whl 安装收集的软件包:virtualenv

然后我得到了:

脚本virtualenv安装在PATH之外的’/Users/brahim/Library/Python/2.7/bin’中。考虑将该目录添加到PATH,或者,如果您不想显示此警告,请使用–no-warn-script-location。

它清楚地说明了它的安装位置以及如何获得它

Same problem: So I just did pip uninstall virtualenv Then pip install virtualenv

pip install virtualenv --user

Collecting virtualenv Using cached https://files.pythonhosted.org/packages/b6/30/96a02b2287098b23b875bc8c2f58071c35d2efe84f747b64d523721dc2b5/virtualenv-16.0.0-py2.py3-none-any.whl Installing collected packages: virtualenv

Then I got this :

The script virtualenv is installed in ‘/Users/brahim/Library/Python/2.7/bin’ which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use –no-warn-script-location.

which clearly says where it is installed and what to do to get it


回答 15

如果您使用的是Linux,请打开您的终端,然后在其中途键入virtualenv,然后使用Tab键自动完成。如果没有自动完成功能,请运行以下命令在系统上安装virtualenv:

mycomp$sudo apt-get install virtualenv
//if you're already super user.
mycomp#apt-get install virtualenv

现在,您可以导航到要创建项目的位置并执行以下操作:

myprj$pip3 install virtualenv    
//to install python 3.5 and above  
myprj$virtualenv venv --python=python3.5  
//to activate virtualenv  
(venv)myprj$source venv/bin/activate  
(venv)myprj$deactivate

If you’re using Linux, open your terminal and type virtualenv halfway and autocomplete with tab key. If there’s no auto-completion install virtualenv on your system by running:

mycomp$sudo apt-get install virtualenv
//if you're already super user.
mycomp#apt-get install virtualenv

You can now navigate to where you want to create your project and do:

myprj$pip3 install virtualenv    
//to install python 3.5 and above  
myprj$virtualenv venv --python=python3.5  
//to activate virtualenv  
(venv)myprj$source venv/bin/activate  
(venv)myprj$deactivate

回答 16

这在ubuntu 18及更高版本中有效(未经先前版本测试):

sudo apt install python3-virtualenv

this works in ubuntu 18 and above (not tested in previous versions):

sudo apt install python3-virtualenv

回答 17

请按照以下基本步骤设置虚拟环境

sudo pip install virtualenv virtualenvwrapper
sudo rm -rf ~/get-pip.py ~/.cache/pip

我们需要更新我们的 ~/.bashrc

export WORKON_HOME=$HOME/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh

~/.bashrc文件只是Shell脚本,只要您启动新终端,Bash就会运行。通常,您使用此文件来设置各种配置。在这种情况下,我们将设置一个名为的环境变量,WORKON_HOME 以指向我们的Python虚拟环境所在的目录。然后,我们从virtualenvwrapper加载任何必要的配置。

要更新~/.bashrc文件,只需使用标准的文本编辑器,nano可能是最容易操作的。一个更简单的解决方案是使用cat命令并完全避免使用编辑器:

echo -e "\n# virtualenv and virtualenvwrapper" >> ~/.bashrc
echo "export WORKON_HOME=$HOME/.virtualenvs" >> ~/.bashrc
echo "source /usr/local/bin/virtualenvwrapper.sh" >> ~/.bashrc

编辑〜/ .bashrc文件后,我们需要重新加载更改:

source ~/.bashrc

现在我们已经安装了virtualenv和virtualenvwrapper,下一步是实际创建Python虚拟环境-我们使用mkvirtualenv命令执行此操作。

mkvirtualenv YOURENV

Follow these basic steps to setup the virtual env

sudo pip install virtualenv virtualenvwrapper
sudo rm -rf ~/get-pip.py ~/.cache/pip

we need to update our ~/.bashrc

export WORKON_HOME=$HOME/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh

The ~/.bashrc file is simply a shell script that Bash runs whenever you launch a new terminal. You normally use this file to set various configurations. In this case, we are setting an environment variable called WORKON_HOME to point to the directory where our Python virtual environments live. We then load any necessary configurations from virtualenvwrapper .

To update your ~/.bashrc file simply use a standard text editor, nano is likely the easiest to operate. A more simple solution is to use the cat command and avoid editors entirely:

echo -e "\n# virtualenv and virtualenvwrapper" >> ~/.bashrc
echo "export WORKON_HOME=$HOME/.virtualenvs" >> ~/.bashrc
echo "source /usr/local/bin/virtualenvwrapper.sh" >> ~/.bashrc

After editing our ~/.bashrc file, we need to reload the changes:

source ~/.bashrc

Now that we have installed virtualenv and virtualenvwrapper , the next step is to actually create the Python virtual environment — we do this using the mkvirtualenv command.

mkvirtualenv YOURENV

回答 18

对我来说,它已安装在以下路径中(在MacOS上为python 2.7):$ HOME / Library / Python / 2.7 / bin

For me it was installed in this path (python 2.7 on MacOS): $HOME/Library/Python/2.7/bin


回答 19

我正在做Angela Yu的在线iOS类,遇到同样的问题,当我尝试运行时也遇到权限被拒绝的错误13 virtualenv --python=/{myPath} {newVirtualEnvName}

我通过以下方法解决了它:

  1. 切换到sudo用户 sudo su
  2. 导航到我的目标文件夹(我希望我的新虚拟环境驻留在其中),即。/ Users / muUserName / Environments /
  3. 运行命令python -m virtualenv python27,其中python27是我的新的虚拟环境的名称
  4. 上面在我的环境文件夹中创建了文件夹pathon27,然后我能够运行以启动我的virtualenvsource python27/bin/activate

I’m doing Angela Yu’s online iOS course and I was getting same problem plus also was getting permission denied error 13 when I was trying to run virtualenv --python=/{myPath} {newVirtualEnvName}

I solved it by:

  1. switching to sudo user sudo su
  2. navigating to my destination folder (where I want my new virtual env to live) ie. /Users/muUserName/Environments/
  3. run command python -m virtualenv python27 where python27 is a name of my new virtual environment
  4. above created folder pathon27 in my Environments folder, and then I was able to run source python27/bin/activate to start my virtualenv

回答 20

简单的答案是,如果您不是我(不是我)的sudo用户,则需要添加bin文件夹(/home/myusername/.local/bin)的路径。因此基本上,命令行会在您键入这些命令的路径中搜索哪个。

export PATH=/home/b18150/.local/bin:/usr/bin:/bin

在这里它将先搜索local/bin然后/usr/bin再搜索/bin

Simple answer is that if you are not a sudo user as I was not one.You need to add path of your bin folder (/home/myusername/.local/bin).So basically the command line searches in which of these path is the command which you have typed.

export PATH=/home/b18150/.local/bin:/usr/bin:/bin

here it will search in local/bin first then /usr/bin and then /bin.


回答 21

我有相同的问题很长时间了。我通过运行以下两个命令解决了这个问题,首先是安装,其次是激活env:

python3 -m pip install virtualenv
python3 -m virtualenv yourenvname

请注意,我使用python3,你可以把它改成只是python如果python3失败。谢谢。

I had the same problem for a long time. I solved it by running these two commands, first is to install second is to activate the env:

python3 -m pip install virtualenv
python3 -m virtualenv yourenvname

Note that I’m using python3, you can change it to just python if python3 fails. Thanks.


回答 22

apt update
apt upgrade
apt install ufw python virtualenv git unzip pv

3个命令,一切正常!

apt update
apt upgrade
apt install ufw python virtualenv git unzip pv

3 commands and everything working!


回答 23

sudo apt-get install python-virtualenv
sudo apt-get install python-virtualenv

在OSX 10.11(El Capitan)中安装Scrapy(系统完整性保护)时,出现“ OSError:[Errno 1] Operation not allow”

问题:在OSX 10.11(El Capitan)中安装Scrapy(系统完整性保护)时,出现“ OSError:[Errno 1] Operation not allow”

我正在尝试通过pip在OSX 10.11(El Capitan)中安装Scrapy Python框架。安装脚本下载所需的模块,并在某些时候返回以下错误:

OSError: [Errno 1] Operation not permitted: '/tmp/pip-nIfswi-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info'

我尝试使用以下命令停用OSX 10.11中的无根功能:

sudo nvram boot-args="rootless=0";sudo reboot

但是当机器重启时,我仍然收到相同的错误。

我的StackExchangers同事有什么线索或想法吗?

如果有帮助,则完整的脚本输出如下:

sudo -s pip install scrapy
Collecting scrapy
  Downloading Scrapy-1.0.2-py2-none-any.whl (290kB)
    100% |████████████████████████████████| 290kB 345kB/s 
Requirement already satisfied (use --upgrade to upgrade): cssselect>=0.9 in /Library/Python/2.7/site-packages (from scrapy)
Requirement already satisfied (use --upgrade to upgrade): queuelib in /Library/Python/2.7/site-packages (from scrapy)
Requirement already satisfied (use --upgrade to upgrade): pyOpenSSL in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from scrapy)
Collecting w3lib>=1.8.0 (from scrapy)
  Downloading w3lib-1.12.0-py2.py3-none-any.whl
Collecting lxml (from scrapy)
  Downloading lxml-3.4.4.tar.gz (3.5MB)
    100% |████████████████████████████████| 3.5MB 112kB/s 
Collecting Twisted>=10.0.0 (from scrapy)
  Downloading Twisted-15.3.0.tar.bz2 (4.4MB)
    100% |████████████████████████████████| 4.4MB 94kB/s 
Collecting six>=1.5.2 (from scrapy)
  Downloading six-1.9.0-py2.py3-none-any.whl
Requirement already satisfied (use --upgrade to upgrade): zope.interface>=3.6.0 in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from Twisted>=10.0.0->scrapy)
Requirement already satisfied (use --upgrade to upgrade): setuptools in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from zope.interface>=3.6.0->Twisted>=10.0.0->scrapy)
Installing collected packages: six, w3lib, lxml, Twisted, scrapy
  Found existing installation: six 1.4.1
    DEPRECATION: Uninstalling a distutils installed project (six) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project.
    Uninstalling six-1.4.1:
Exception:
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/basecommand.py", line 223, in main
status = self.run(options, args)
  File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/commands/install.py", line 299, in run
root=options.root_path,
  File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_set.py", line 640, in install
requirement.uninstall(auto_confirm=True)
  File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_install.py", line 726, in uninstall
paths_to_remove.remove(auto_confirm)
  File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_uninstall.py", line 125, in remove
renames(path, new_path)
  File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/utils/__init__.py", line 314, in renames
shutil.move(old, new)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move
copy2(src, real_dst)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2
copystat(src, dst)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat
os.chflags(dst, st.st_flags)
OSError: [Errno 1] Operation not permitted: '/tmp/pip-nIfswi-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info'

I’m trying to install Scrapy Python framework in OSX 10.11 (El Capitan) via pip. The installation script downloads the required modules and at some point returns the following error:

OSError: [Errno 1] Operation not permitted: '/tmp/pip-nIfswi-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info'

I’ve tried to deactivate the rootless feature in OSX 10.11 with the command:

sudo nvram boot-args="rootless=0";sudo reboot

but I still get the same error when the machine reboots.

Any clue or idea from my fellow StackExchangers?

If it helps, the full script output is the following:

sudo -s pip install scrapy
Collecting scrapy
  Downloading Scrapy-1.0.2-py2-none-any.whl (290kB)
    100% |████████████████████████████████| 290kB 345kB/s 
Requirement already satisfied (use --upgrade to upgrade): cssselect>=0.9 in /Library/Python/2.7/site-packages (from scrapy)
Requirement already satisfied (use --upgrade to upgrade): queuelib in /Library/Python/2.7/site-packages (from scrapy)
Requirement already satisfied (use --upgrade to upgrade): pyOpenSSL in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from scrapy)
Collecting w3lib>=1.8.0 (from scrapy)
  Downloading w3lib-1.12.0-py2.py3-none-any.whl
Collecting lxml (from scrapy)
  Downloading lxml-3.4.4.tar.gz (3.5MB)
    100% |████████████████████████████████| 3.5MB 112kB/s 
Collecting Twisted>=10.0.0 (from scrapy)
  Downloading Twisted-15.3.0.tar.bz2 (4.4MB)
    100% |████████████████████████████████| 4.4MB 94kB/s 
Collecting six>=1.5.2 (from scrapy)
  Downloading six-1.9.0-py2.py3-none-any.whl
Requirement already satisfied (use --upgrade to upgrade): zope.interface>=3.6.0 in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from Twisted>=10.0.0->scrapy)
Requirement already satisfied (use --upgrade to upgrade): setuptools in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from zope.interface>=3.6.0->Twisted>=10.0.0->scrapy)
Installing collected packages: six, w3lib, lxml, Twisted, scrapy
  Found existing installation: six 1.4.1
    DEPRECATION: Uninstalling a distutils installed project (six) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project.
    Uninstalling six-1.4.1:
Exception:
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/basecommand.py", line 223, in main
status = self.run(options, args)
  File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/commands/install.py", line 299, in run
root=options.root_path,
  File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_set.py", line 640, in install
requirement.uninstall(auto_confirm=True)
  File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_install.py", line 726, in uninstall
paths_to_remove.remove(auto_confirm)
  File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_uninstall.py", line 125, in remove
renames(path, new_path)
  File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/utils/__init__.py", line 314, in renames
shutil.move(old, new)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move
copy2(src, real_dst)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2
copystat(src, dst)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat
os.chflags(dst, st.st_flags)
OSError: [Errno 1] Operation not permitted: '/tmp/pip-nIfswi-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info'

回答 0

我也认为完全没有必要开始入侵OSX。

我能够解决它

brew install python

看来,使用新版El Capitan随附的python / pip会有一些问题。

I also think it’s absolutely not necessary to start hacking OS X.

I was able to solve it doing a

brew install python

It seems that using the python / pip that comes with new El Capitan has some issues.


回答 1

pip install --ignore-installed six

会做到的。

资料来源:github.com/pypa/pip/issues/3165

pip install --ignore-installed six

Would do the trick.

Source: github.com/pypa/pip/issues/3165


回答 2

正如其他答案所说,这是由于新的系统完整性保护,但我认为其他答案过于复杂。

如果您只想在当前用户中使用该软件包,则可以使用该--user标志,而无需禁用SIP,就可以很好地安装它。像这样:

sudo pip install --user packagename

As the other answers said, it’s because of the new System Integrity Protection, but I believe the other answers are overcomplicated.

If you’re only gonna use that package in the current user, you should be able to install it just fine, without the need to disable the SIP, by using the --user flag. Like this:

sudo pip install --user packagename

回答 3

高投票答案对我不起作用,似乎对El Capitan用户有效。但是对于MacOS Sierra用户,请尝试以下步骤

  1. brew install python
  2. sudo pip install --user <package name>

The high voted answers didn’t work for me, it seems to work for El Capitan users. But for MacOS Sierra users try the following steps

  1. brew install python
  2. sudo pip install --user <package name>

回答 4

警告事项

强烈建议不要在Mac上修改系统Python;可能会发生许多问题。

您的特定错误表明安装程序存在解决Scrapy依赖关系的问题,而不影响当前的Python安装。该系统使用Python执行许多基本任务,因此保持系统安装的稳定性和Apple最初安装的位置非常重要

在绕过内置安全性之前,我还将穷尽所有其他可能性

包管理器解决方案:

请先研究Python虚拟化工具,例如virtualenv;这样可以安全地进行实验。

在不与Mac OS冲突的情况下使用语言和软件的另一个有用工具是Homebrew。与MacPortsFink一样Homebrew是Mac的软件包管理器。,对于安全尝试许多其他语言和工具很有用。

“自行运行”软件安装:

如果您不喜欢包管理器方法,则可以使用该/usr/local路径或创建/opt/local用于安装备用Python安装的目录,然后在中修复路径.bashrc。请注意,您必须为这些解决方案启用root。

无论如何如何:

如果您绝对必须禁用安全检查(并且我衷心希望它用于解决系统语言和资源之外的其他问题),则可以暂时禁用它,然后使用本文中有关如何禁用系统的一些技术来重新启用它完整性保护

Warnings

I would suggest very strongly against modifying the system Python on Mac; there are numerous issues that can occur.

Your particular error shows that the installer has issues resolving the dependencies for Scrapy without impacting the current Python installation. The system uses Python for a number of essential tasks, so it’s important to keep the system installation stable and as originally installed by Apple.

I would also exhaust all other possibilities before bypassing built in security.

Package Manager Solutions:

Please look into a Python virtualization tool such as virtualenv first; this will allow you to experiment safely.

Another useful tool to use languages and software without conflicting with your Mac OS is Homebrew. Like MacPorts or Fink, Homebrew is a package manager for Mac, and is useful for safely trying lots of other languages and tools.

“Roll your own” Software Installs:

If you don’t like the package manager approach, you could use the /usr/local path or create an /opt/local directory for installing an alternate Python installation and fix up your paths in your .bashrc. Note that you’ll have to enable root for these solutions.

How to do it anyway:

If you absolutely must disable the security check (and I sincerely hope it’s for something other than messing with the system languages and resources), you can disable it temporarily and re-enable it using some of the techniques in this post on how to Disable System Integrity-Protection.


回答 5

这对我有用:

   sudo pip install scrapy --ignore-installed six

This did the trick for me:

   sudo pip install scrapy --ignore-installed six

回答 6

您应禁用“系统完整性保护”,这是El Capitan的一项新功能。

首先,您应该在终端上运行无根配置命令

# nvram boot-args="rootless=0"
# reboot

然后,您应该在恢复分区的终端(恢复操作系统)上运行以下命令

# csrutil disable
# reboot

我刚刚解决了我的问题。我不确定第一部分是否必要。随便尝试。

– 警告

一切正常后,您应该再次启用SIP。

只需再次重新启动进入恢复模式并在终端中运行

# csrutil enable

csrutil:配置系统完整性保护

You should disable “System Integrity Protection” which is a new feature in El Capitan.

First, you should run the command for rootless config on your terminal

# nvram boot-args="rootless=0"
# reboot

Then, you should run the command below on recovery partition’s terminal (Recovery OS)

# csrutil disable
# reboot

I’ve just solved my problem like that. I’m not sure that the first part is necessary. Try as you like.

–WARNING

You should enable SIP again after everything works;

Simply reboot again into Recovery Mode and run in terminal

# csrutil enable

csrutil: Configuring System Integrity Protection


回答 7

我试图通过El Capitan中的pip安装AWS,但出现此错误

OSError:[Errno 1]不允许操作:’/var/folders/wm/jhnj0g_s16gb36y8kwvrgm7h0000gp/T/pip-wTnb_D-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six- 1.4.1-py2.7.egg-info’

我在这里找到答案

sudo -H pip install awscli --upgrade --ignore-installed six

这个对我有用 :)

I tried to install AWS via pip in El Capitan but this error appear

OSError: [Errno 1] Operation not permitted: ‘/var/folders/wm/jhnj0g_s16gb36y8kwvrgm7h0000gp/T/pip-wTnb_D-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info’

I found the answer here

sudo -H pip install awscli --upgrade --ignore-installed six

It works for me :)


回答 8

我在MacOS Sierra上遇到了相同的错误。我按照以下步骤操作,成功安装了可伸缩的软件包。

1. sudo pip install --ignore-installed six
2. sudo pip install --ignore-installed scrapy

MacBook-Air:~ shree$ scrapy version
Scrapy 1.4.0

I was getting the same error on on my MacOS Sierra. I followed these steps and successfully able to install scarpy package.

1. sudo pip install --ignore-installed six
2. sudo pip install --ignore-installed scrapy

MacBook-Air:~ shree$ scrapy version
Scrapy 1.4.0

回答 9

这对我有用。

sudo pip install –ignore-installed scrapy

This did the trick for me.

sudo pip install –ignore-installed scrapy


回答 10

尝试了一些答案的组合,最终成功了:

sudo -H pip install --upgrade --ignore-installed awsebcli

干杯

Tried a combination of some answers and this eventually worked:

sudo -H pip install --upgrade --ignore-installed awsebcli

Cheers


回答 11

再次安装python:

brew安装python

再试一次:

须藤点安装刮

为我工作,希望它可以帮助

install python again:

brew install python

try it again:

sudo pip install scrapy

works for me, hope it can help


回答 12

重新启动Mac->在启动提示音后按住“ Command + R”->打开OS X实用程序->打开终端并键入“ csrutil disable”->重新启动OS X->打开终端并检查“ csrutil status”

Restart Mac -> hold down “Command + R” after the startup chime -> Opens OS X Utilities -> Open Terminal and type “csrutil disable” -> Reboot OS X -> Open Terminal and check “csrutil status”


回答 13

这个命令可以很好地工作:D

sudo -H pip install –upgrade package_name –ignore-installed六

This command would work perfectly fine :D

sudo -H pip install –upgrade package_name –ignore-installed six


回答 14

如果您尝试使用pip而不是pip3在python2文件夹中安装python3 lib,有时可能会实现这种行为。

Sometimes such behavior may be achieved if you try to install python3 lib in python2 folder using pip instead of pip3.


回答 15

  1. -关闭SIP(系统完整性保护)-然后重新启动,使用命令+ R进入调试模式,然后选择终端:csrutil disable reboot

2。

sudo C_INCLUDE_PATH = /应用程序/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include/libxml2:/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX .platform / Developer / SDKs / MacOSX10.11.sdk / usr / include / libxml2 / libxml:/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/包括pip install scrapy –ignore-installed 6

3.-然后删除旧的六个,重新安装sudo rm -rf /Library/Python/2.7/site-packages/six* sudo rm -rf /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/ lib / python / six * sudo pip安装六

4.-然后将其设置回csrutil启用重新启动

-cr脚的作品现在

  1. — close SIP(system Integrity Protection) — then reboot, use command +R to enter debug mode, then select terminal: csrutil disable reboot

2.

sudo C_INCLUDE_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include/libxml2 :/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include/libxml2/libxml :/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include pip install scrapy –ignore-installed six

3. — then remove old six, install it again sudo rm -rf /Library/Python/2.7/site-packages/six* sudo rm -rf /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six* sudo pip install six

4. — then set it back csrutil enable reboot

— crappy works now


回答 16

它对我有用:

pip install scrapy --user -U

it work for me:

pip install scrapy --user -U

回答 17

我在其他地方缺少依赖项,因此我为项目安装了其他要求,如下所示:

pip install --user -r requirements.txt

I was missing a dependency somewhere else along the line, so I installed the other requirements for the project like this:

pip install --user -r requirements.txt

Virtualenvs中的参考损坏

问题:Virtualenvs中的参考损坏

我最近在Mac上安装了许多点文件以及其他一些应用程序(我改为使用iTerm而不是Terminal,将Sublime设置为默认文本编辑器),但是此后,尽管它们的文件夹位于.virtualenvs中,但我所有的虚拟环境都停止了工作仍然在那里,每当我尝试在其中运行任何命令时,它们都会给出以下错误:

dyld: Library not loaded: @executable_path/../.Python
  Referenced from: /Users/[user]/.virtualenvs/modclass/bin/python
  Reason: image not found
Trace/BPT trap: 5

我已经删除了所有与dotfiles相关的文件,并将.bash_profile还原到以前的状态,但是问题仍然存在。是否有任何方法可以诊断问题或以简单的方式解决问题(例如,无需再次创建所有虚拟环境)?

I recently installed a bunch of dotfiles on my Mac along with some other applications (I changed to iTerm instead of Terminal, and Sublime as my default text editor) but ever since, all my virtual environments have stopped working, although their folders inside .virtualenvs are still there and they give the following error whenever I try to run anything in them:

dyld: Library not loaded: @executable_path/../.Python
  Referenced from: /Users/[user]/.virtualenvs/modclass/bin/python
  Reason: image not found
Trace/BPT trap: 5

I have removed all the files related to dotfiles and have restored my .bash_profile to what it was before, but the problem persists. Is there any way to diagnose the problem or solve it in an easy way (e.g. not requiring to create all the virtualenvs all over again)?


回答 0

我在这里找到了解决问题的方法,所以所有功劳都归功于作者。

要点是,当您创建一个virtualenv时,会为安装了Homebrew的Python创建许多符号链接。

这是一个例子:

$ ls -la ~/.virtualenvs/my-virtual-env
...
lrwxr-xr-x  1 ryan staff   78 Jun 25 13:21 .Python -> /usr/local/Cellar/python/2.7.7/Frameworks/Python.framework/Versions/2.7/Python
...

当您使用Homebrew升级Python然后运行时brew cleanup,virtualenv中的符号链接指向不再存在的路径(因为Homebrew删除了它们)。

符号链接需要指向新安装的Python:

lrwxr-xr-x  1 ryan staff   78 Jun 25 13:21 .Python -> /usr/local/Cellar/python/2.7.8_1/Frameworks/Python.framework/Versions/2.7/Python

解决方案是删除virtualenv中的符号链接,然后重新创建它们:

find ~/.virtualenvs/my-virtual-env/ -type l -delete
virtualenv ~/.virtualenvs/my-virtual-env

最好在删除链接之前先检查哪些链接将被删除:

find ~/.virtualenvs/my-virtual-env/ -type l

我认为,最好只删除损坏的符号链接。您可以使用GNU执行此操作find

gfind ~/.virtualenvs/my-virtual-env/ -type l -xtype l -delete

find如果尚未安装GNU ,可以使用Homebrew 进行安装:

brew install findutils

请注意,默认情况下,随Homebrew一起安装的GNU程序通常以字母开头g。这是为了避免遮盖findOS X附带的二进制文件。

I found the solution to the problem here, so all credit goes to the author.

The gist is that when you create a virtualenv, many symlinks are created to the Homebrew installed Python.

Here is one example:

$ ls -la ~/.virtualenvs/my-virtual-env
...
lrwxr-xr-x  1 ryan staff   78 Jun 25 13:21 .Python -> /usr/local/Cellar/python/2.7.7/Frameworks/Python.framework/Versions/2.7/Python
...

When you upgrade Python using Homebrew and then run brew cleanup, the symlinks in the virtualenv point to paths that no longer exist (because Homebrew deleted them).

The symlinks needs to point to the newly installed Python:

lrwxr-xr-x  1 ryan staff   78 Jun 25 13:21 .Python -> /usr/local/Cellar/python/2.7.8_1/Frameworks/Python.framework/Versions/2.7/Python

The solution is to remove the symlinks in the virtualenv and then recreate them:

find ~/.virtualenvs/my-virtual-env/ -type l -delete
virtualenv ~/.virtualenvs/my-virtual-env

It’s probably best to check what links will be deleted first before deleting them:

find ~/.virtualenvs/my-virtual-env/ -type l

In my opinion, it’s even better to only delete broken symlinks. You can do this using GNU find:

gfind ~/.virtualenvs/my-virtual-env/ -type l -xtype l -delete

You can install GNU find with Homebrew if you don’t already have it:

brew install findutils

Notice that by default, GNU programs installed with Homebrew tend to be prefixed with the letter g. This is to avoid shadowing the find binary that ships with OS X.


回答 1

在尝试了几件事之后,这对我有用:

转到您的virtualenv目录(但不要运行workon):

cd ~/.virtualenv/name_of_broken_venv

现在删除这些文件:

rm -rf .Python bin/python* lib/python2.7/* include/python2.7

然后重建您的venv,运行:

virtualenv .
workon name_of_broken_venv
pip freeze

现在,您应该再次看到已安装软件包的列表。

After trying a few things, this worked for me:

go to your virtualenv directory (but don’t run workon):

cd ~/.virtualenv/name_of_broken_venv

Now delete these files:

rm -rf .Python bin/python* lib/python2.7/* include/python2.7

Then to rebuild your venv, run:

virtualenv .
workon name_of_broken_venv
pip freeze

You should now see a list of your installed packages again.


回答 2

当我从Snow Leopard更新到Mac OS X Mavericks时,就会发生这种情况。我也必须事先重新安装brew。希望您使用pip为项目运行了冻结命令。

若要解决,您必须更新虚拟环境指向的路径。

  • 使用brew安装python版本:

brew install python

  • 重新安装virtualenvwrapper。

pip install --upgrade virtualenvwrapper

  • 删除了旧的虚拟环境:

rmvirtualenv old_project

  • 创建一个新的虚拟环境:

mkvirtualenv new_project

  • 在新的虚拟环境上工作

workon new_project

  • 使用pip安装新项目的要求。

pip install -r requirements.txt

这应该使项目保持以前的状态。

This occurred when I updated to Mac OS X Mavericks from Snow Leopard. I had to re-install brew beforehand too. Hopefully you ran the freeze command for your project with pip.

To resolve, you have to update the paths that the virtual environment points to.

  • Install a version of python with brew:

brew install python

  • Re-install virtualenvwrapper.

pip install --upgrade virtualenvwrapper

  • Removed the old virtual environment:

rmvirtualenv old_project

  • Create a new virtual environment:

mkvirtualenv new_project

  • Work on new virtual environment

workon new_project

  • Use pip to install the requirements for the new project.

pip install -r requirements.txt

This should leave the project as it was before.


回答 3

@Chris Wedgwood保留更新版本的答案site-packages(保留已安装的软件包)

cd ~/.virtualenv/name_of_broken_venv


mv lib/python2.7/site-packages ./    
rm -rf .Python bin lib include
virtualenv .
rm -rf lib/python2.7/site-packages
mv ./site-packages lib/python2.7/

A update version @Chris Wedgwood‘s answer for keeping site-packages (keeping packages installed)

cd ~/.virtualenv/name_of_broken_venv


mv lib/python2.7/site-packages ./    
rm -rf .Python bin lib include
virtualenv .
rm -rf lib/python2.7/site-packages
mv ./site-packages lib/python2.7/

回答 4

看来解决此问题的正确方法是运行

 pip install --upgrade virtualenv

用Homebrew升级python之后。

对于安装类似python的任何公式,该公式应该是一个通用过程,它具有自己的包管理系统。当您安装brew install python,在安装pythonpipeasy_installvirtualenv等。因此,如果这些工具可以自我更新,那么最好先尝试这样做,然后再将“自制”视为问题的根源。

It appears the proper way to resolve this issue is to run

 pip install --upgrade virtualenv

after you have upgraded python with Homebrew.

This should be a general procedure for any formula that installs something like python, which has it’s own package management system. When you install brew install python, you install python and pip and easy_install and virtualenv and so on. So, if those tools can be self-updated, it’s best to try to do so before looking to Homebrew as the source of problems.


回答 5

如果这是由brew upgrade升级其Python 引起的,并且可以降级到以前的版本,请尝试brew switch python [previous version],例如brew switch python 3.6.5从这里。

If this was caused by a brew upgrade that upgraded its Python, and you’re ok with downgrading to the previous version, try brew switch python [previous version], eg brew switch python 3.6.5. From here.


回答 6

virtualenvwrapper指令

如已接受的答案所示,根本原因可能是自制程序更新,这意味着您的virtualenv符号链接指向断开的python路径-请在此处查看详细信息。

对于每个虚拟环境,您需要重新分配符号链接以指向正确的python路径(在Brew酒窖中)。这是使用virtualenvwrapper进行操作的方法。在这里,我正在更新一个名为“ my-example-env”的虚拟环境。

cd ~/PYTHON_ENVS
find ./my-example-env -type l -delete
mkvirtualenv my-example-env

全做完了。

virtualenvwrapper instructions

As indicated in the accepted answer, the root cause is likely a homebrew update that means your virtualenv symlinks are pointing at broken python paths – see details here.

For each virtual env, you need to reassign the symlinks to point at the correct python path (in brew cellar). Here is how to do it with virtualenvwrapper. Here I am updating a virtual env called “my-example-env”.

cd ~/PYTHON_ENVS
find ./my-example-env -type l -delete
mkvirtualenv my-example-env

All done.


回答 7

任何使用pipenv的人(并且应该使用!)都可以简单地使用以下两个命令-无需激活venv:

rm -rf `pipenv --venv` # remove the broken venv
pipenv install --dev   # reinstall the venv from pipfile 

Anyone who is using pipenv (and you should!) can simply use these two commands — without having the venv activated:

rm -rf `pipenv --venv` # remove the broken venv
pipenv install --dev   # reinstall the venv from pipfile 

回答 8

如果您破坏了python3,请尝试brew upgrade python3为我修复它。

If you’ve busted python3 just try brew upgrade python3 that fixed it for me.


回答 9

我最近遇到了这个问题。以上解决方案均不适合我。看来这实际上不是Python的问题。当我运行

aws s3 ls

时,出现以下错误:

dyld: Library not loaded: @executable_path/../.Python

这意味着库aws可执行文件指向的是不存在或已损坏,因此我aws-cli按照此链接的说明进行了卸载并重新安装,并且有效!

I recently faced this. None of the above solutions worked for me. Seems it wasn’t actually Python’s problem. When I was running

aws s3 ls

I was getting following error:

dyld: Library not loaded: @executable_path/../.Python

This means, the library aws executable is pointing towards is either doesn’t exist or is corrupted, thus I uninstalled and reinstalled aws-cli following instructions from this link and it worked!!


回答 10

我(MacOS用户)遇到的问题是,brew将Python和virtualenvs链接更新为已删除的旧版本。

我们可以通过以下方式进行检查和修复

>> ls -al ~/.virtualenvs/<your-virtual-env>/.Python
.Python -> /usr/local/Cellar/python/<old-version>/Frameworks/Python.framework/Versions/3.7/Python
>> rm ~/.virtualenvs/<your-virtual-env>/.Python
>> ln -s  /usr/local/Cellar/python/<new-version>/Frameworks/Python.framework/Versions/3.7/Python ~/.virtualenvs/<your-virtual-env>/.Python

The problem for me(a MacOS user) is that brew updated the Python and virtualenvs links to the old version which was deleted.

We can check and fix it by

>> ls -al ~/.virtualenvs/<your-virtual-env>/.Python
.Python -> /usr/local/Cellar/python/<old-version>/Frameworks/Python.framework/Versions/3.7/Python
>> rm ~/.virtualenvs/<your-virtual-env>/.Python
>> ln -s  /usr/local/Cellar/python/<new-version>/Frameworks/Python.framework/Versions/3.7/Python ~/.virtualenvs/<your-virtual-env>/.Python

回答 11

我有一个类似的问题,我只是通过使用 virtualenv .

I had a similar issue and i solved it by just rebuilding the virtual environment with virtualenv .


回答 12

使用Python 2.7.10。

一个命令即可virtualenv path-to-env完成。文件资料

$ virtualenv path-to-env
Overwriting path-to-env/lib/python2.7/orig-prefix.txt with new content
New python executable in path-to-env/bin/python2.7
Also creating executable in path-to-env/bin/python
Installing setuptools, pip, wheel...done.

Using Python 2.7.10.

A single command virtualenv path-to-env does it. documentation

$ virtualenv path-to-env
Overwriting path-to-env/lib/python2.7/orig-prefix.txt with new content
New python executable in path-to-env/bin/python2.7
Also creating executable in path-to-env/bin/python
Installing setuptools, pip, wheel...done.

回答 13

由于python的Homebrew重新安装(因此损坏的符号链接)以及我之前完成的一些“ sudo pip安装”,我的虚拟环境也损坏了。Weizhong的技巧对解决问题非常有用,而无需重新安装软件包。对于混合权限问题,我还必须执行以下操作。

须藤chown -R my_username lib / python2.7 / site-packages

I had a broken virtual env due to a Homebrew reinstall of python (thereby broken symlinks) and also a few “sudo pip install”s I had done earlier. Weizhong’s tips were very helpful in fixing the issues without having to reinstall packages. I also had to do the following for the mixed permissions problem.

sudo chown -R my_username lib/python2.7/site-packages


回答 14

Virtualenvs已损坏。有时,简单的方法是删除venv文件夹并重新创建virutalenvs。

Virtualenvs are broken. Sometimes simple way is to delete venv folders and recreate virutalenvs.


回答 15

如果您使用pipenv,只需pipenv --rm解决即可。

If you using pipenv, just doing pipenv --rm solves the problem.


回答 16

在OSX Catalina上升级brew后,我遇到了同样的问题。

在尝试了一堆东西之后,我发现以下是最佳和简便的解决方案。

首先,删除虚拟环境。(可选的)

find myvirtualenv -type l -delete

然后重新创建一个新的virtualenv

virtualenv myvirtualenv

参考:https : //www.jeremycade.com/python/osx/homebrew/2015/03/02/fixing-virtualenv-after-a-python-upgrade/

I was facing the same issue after upgrading brew on my OSX Catalina.

After trying bunch of stuffs, I find the following is the best and easy solution.

At first, delete the virtual env. (Optional)

find myvirtualenv -type l -delete

then recreate a new virtualenv

virtualenv myvirtualenv

Reference: https://www.jeremycade.com/python/osx/homebrew/2015/03/02/fixing-virtualenv-after-a-python-upgrade/


回答 17

接受的答案对我不起作用:该文件$WORKON_HOME/*/bin/python2.7不再是符号链接,而是功能全面的可执行文件:

$ file $WORKON_HOME/*/bin/python2.7
/Users/sds/.virtualenvs/.../bin/python2.7: Mach-O 64-bit executable x86_64
...

a,解决方案是完全删除所有虚拟环境并从头开始重新创建。

供参考:

deactivate
pip install --user virtualenv virtualenvwrapper
pip install --user --upgrade virtualenv virtualenvwrapper
for ve in $(lsvirtualenv -b); do
  # assume that each VE is associated with a project
  # and the project has the requirements.txt file
  project=$(cat $WORKON_HOME/$ve/.project)
  rmvirtualenv $ve
  mkvirtualenv -a $project -r requirements.txt $ve
done

The accepted answer does not work for me: the file $WORKON_HOME/*/bin/python2.7 is no longer a symlink, it is a full-fledged executable:

$ file $WORKON_HOME/*/bin/python2.7
/Users/sds/.virtualenvs/.../bin/python2.7: Mach-O 64-bit executable x86_64
...

The solution is, alas, to completely remove and re-create from scratch all the virtual environments.

For the reference:

deactivate
pip install --user virtualenv virtualenvwrapper
pip install --user --upgrade virtualenv virtualenvwrapper
for ve in $(lsvirtualenv -b); do
  # assume that each VE is associated with a project
  # and the project has the requirements.txt file
  project=$(cat $WORKON_HOME/$ve/.project)
  rmvirtualenv $ve
  mkvirtualenv -a $project -r requirements.txt $ve
done

回答 18

简单地升级python3对我有用:

brew upgrade python3

Simply upgrading python3 worked for me:

brew upgrade python3

回答 19

我尝试了前几种方法,但对我而言,它们却无济于事,这些方法正试图使毒素发挥作用。最终有效的是:

sudo pip install tox

即使已经安装了tox。输出终止于:

Successfully built filelock
Installing collected packages: py, pluggy, toml, filelock, tox
Successfully installed filelock-3.0.10 pluggy-0.11.0 py-1.8.0 toml-0.10.0 tox-3.9.0

I tried the top few methods, but they didn’t work, for me, which were trying to make tox work. What eventually worked was:

sudo pip install tox

even if tox was already installed. The output terminated with:

Successfully built filelock
Installing collected packages: py, pluggy, toml, filelock, tox
Successfully installed filelock-3.0.10 pluggy-0.11.0 py-1.8.0 toml-0.10.0 tox-3.9.0

回答 20

对我来说,解决此问题的方法只是卸载python3和pipenv,然后重新安装它们。

brew uninstall pipenv
brew uninstall python3
brew install python3 
brew install pipenv

What fixed it for me was just uninstalling python3 and pipenv then reinstalling them.

brew uninstall pipenv
brew uninstall python3
brew install python3 
brew install pipenv

回答 21

这里所有的答案都很棒,我尝试了Ryan,Chris上面提到的几种解决方案,但无法解决问题,因此必须采取快速而肮脏的方法。

  1. rm -rf <project dir>(或者mv <project dir> <backup projct dir>如果您想保留备份)
  2. git clone <project git url>
  3. 继续!

这里没有什么新奇的东西,但是它使生活更轻松!

All the answers are great here, I tried a couple of solutions mentioned above by Ryan, Chris and couldn’t resolve the issue, so had to follow a quick and dirty way.

  1. rm -rf <project dir> (or mv <project dir> <backup projct dir> if you want to keep a backup)
  2. git clone <project git url>
  3. Move on!

Nothing novel here, but it makes life easier!


回答 22

我确定我晚会晚了,但是我想说,解决这个问题比这里讨论的要简单得多。

您可以轻松地重新生成虚拟环境,而无需删除/编辑任何内容。假设您调用了损坏的环境,则env_to_fix可以执行以下操作:

mkvirtualenv env_to_fix

这将重新生成链接并修复环境,而无需将当前状态转储到某个位置并进行恢复。

I am sure I am late to the party but I want to say that the resolution of this problem is much simpler than discussed here.

You can easily regenerate the virtual environment without having to delete/edit anything. Assuming that your broken environment is called env_to_fix you can just to the following:

mkvirtualenv env_to_fix

This will regenerate the links and fix the environment without the need to dump the current status somewhere and restore it.


回答 23

当我在Mac上将python运行时从2指向3时,遇到了相同的问题,将别名python指向python 3路径。然后,我重新创建一个新的virtualenv并重新安装我的项目所需的那些软件包。对于我的用例,我有一个写给Google工作表的python程序。清理一些与python 2实现不同的程序包,然后一切又开始起作用。

I came across the same issue when I was pointing my python run time from 2 to 3 on my mac, pointing the alias python to python 3 path. I then recreate a new virtualenv and re-install those packages i need for my project. For my use case i have had a python program writing to google sheet. Clean up a few packages that are different from python 2 implementation and wa la, things started working again.


无法在Mac OS X 10.9上安装Lxml

问题:无法在Mac OS X 10.9上安装Lxml

我想安装Lxml,以便随后可以安装Scrapy。

今天更新Mac时,不允许我重新安装lxml,但出现以下错误:

In file included from src/lxml/lxml.etree.c:314:
/private/tmp/pip_build_root/lxml/src/lxml/includes/etree_defs.h:9:10: fatal error: 'libxml/xmlversion.h' file not found
#include "libxml/xmlversion.h"
         ^
1 error generated.
error: command 'cc' failed with exit status 1

我尝试使用brew安装libxml2和libxslt,两者都安装良好,但仍然无法安装lxml。

上次安装时,我需要在Xcode上启用开发人员工具,但是由于将其更新为Xcode 5,因此不再提供该选项。

有人知道我需要做什么吗?

I want to install Lxml so I can then install Scrapy.

When I updated my Mac today it wouldn’t let me reinstall lxml, I get the following error:

In file included from src/lxml/lxml.etree.c:314:
/private/tmp/pip_build_root/lxml/src/lxml/includes/etree_defs.h:9:10: fatal error: 'libxml/xmlversion.h' file not found
#include "libxml/xmlversion.h"
         ^
1 error generated.
error: command 'cc' failed with exit status 1

I have tried using brew to install libxml2 and libxslt, both installed fine but I still cannot install lxml.

Last time I was installing I needed to enable the developer tools on Xcode but since its updated to Xcode 5 it doesnt give me that option anymore.

Does anyone know what I need to do?


回答 0

您应该为xcode安装或升级命令行工具。在终端上尝试一下:

xcode-select --install

You should install or upgrade the commandline tool for xcode. Try this in a terminal:

xcode-select --install

回答 1

我通过安装和链接libxml2以及libxslt通过brew 在优胜美地上解决了这个问题:

brew install libxml2
brew install libxslt
brew link libxml2 --force
brew link libxslt --force

如果使用此方法解决了问题,但稍后又弹出,则可能需要以上四行之前运行它:

brew unlink libxml2
brew unlink libxslt

如果您在Homebrew上遇到权限错误,尤其是在El Capitan上,则这是一个有用的文档。本质上,无论OS X是什么版本,都请尝试运行:

sudo chown -R $(whoami):admin /usr/local

I solved this issue on Yosemite by both installing and linking libxml2 and libxslt through brew:

brew install libxml2
brew install libxslt
brew link libxml2 --force
brew link libxslt --force

If you have solved the problem using this method but it pops up again at a later time, you might need to run this before the four lines above:

brew unlink libxml2
brew unlink libxslt

If you are having permission errors with Homebrew, especially on El Capitan, this is a helpful document. In essence, regardless of OS X version, try running:

sudo chown -R $(whoami):admin /usr/local

回答 2

您可以通过在命令行上运行此命令来解决问题:

 STATIC_DEPS=true pip install lxml

它肯定帮助了我。文档说明

You may solve your problem by running this on the commandline:

 STATIC_DEPS=true pip install lxml

It sure helped me. Explanations on docs


回答 3

我尝试了上面的大多数解决方案,但没有一个对我有用。我正在运行Yosemite 10.10,唯一适用于我的解决方案是在终端中键入以下内容:

sudo CPATH=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/include/libxml2 CFLAGS=-Qunused-arguments CPPFLAGS=-Qunused-arguments pip install lxml

编辑:如果您使用virtualenv,则不需要开头的sudo。

I tried most of the solutions above, but none of them worked for me. I’m running Yosemite 10.10, the only solution that worked for me was to type this in the terminal:

sudo CPATH=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/include/libxml2 CFLAGS=-Qunused-arguments CPPFLAGS=-Qunused-arguments pip install lxml

EDIT: If you are using virtualenv, the sudo in beginning is not needed.


回答 4

这也困扰了我一段时间。我对python distutils等的内部知识不了解,但是这里的include路径是错误的。我进行了以下丑陋的修改,直到python lxml人员可以进行适当的修复为止。

sudo ln -s  /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/include/libxml2/libxml/ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/include/libxml

This has been bothering me as well for a while. I don’t know the internals enough about python distutils etc, but the include path here is wrong. I made the following ugly hack to hold me over until the python lxml people can do the proper fix.

sudo ln -s  /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/include/libxml2/libxml/ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/include/libxml

回答 5

全局安装… OS X 10.9.2

xcode-select --install
sudo easy_install pip
sudo CPATH=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/include/libxml2 CFLAGS=-Qunused-arguments CPPFLAGS=-Qunused-arguments pip install lxml

Installing globally… OS X 10.9.2

xcode-select --install
sudo easy_install pip
sudo CPATH=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/include/libxml2 CFLAGS=-Qunused-arguments CPPFLAGS=-Qunused-arguments pip install lxml

回答 6

http://lxml.de/installation.html上的安装说明说明:

为了加快测试环境(例如,在持续集成服务器上)的构建速度,请通过设置CFLAGS环境变量来禁用C编译器优化:

CFLAGS="-O0" pip install lxml

instalation instructions on http://lxml.de/installation.html explain:

To speed up the build in test environments, e.g. on a continuous integration server, disable the C compiler optimisations by setting the CFLAGS environment variable:

CFLAGS="-O0" pip install lxml

回答 7

上面的这些在10.9.2上都不适合我,因为编译因以下错误而失败:

clang: error: unknown argument: '-mno-fused-madd' 

这实际上导致最干净的解决方案(请参见[1]中的更多详细信息):

export CFLAGS=-Qunused-arguments
export CPPFLAGS=-Qunused-arguments

pip install lxml

或跟随如果全球安装

sudo pip install lxml

[1] lang错误:未知参数:’-mno-fused-madd’(python软件包安装失败)

None of the above worked for me on 10.9.2, as compilation bails out with following error:

clang: error: unknown argument: '-mno-fused-madd' 

Which actually lead to cleanest solution (see more details in [1]):

export CFLAGS=-Qunused-arguments
export CPPFLAGS=-Qunused-arguments

pip install lxml

or following if installing globally

sudo pip install lxml

[1] clang error: unknown argument: ‘-mno-fused-madd’ (python package installation failure)


回答 8

xcode-select --install
sudo easy_install pip
sudo pip install lxml
xcode-select --install
sudo easy_install pip
sudo pip install lxml

回答 9

Yosemite通过运行以下命令解决了这个问题:

xcode-select install #this may take several minutes.
pip install lxml

I solved this issue on Yosemite by running the following commands:

xcode-select install #this may take several minutes.
pip install lxml

回答 10

对于自制软件,libxml2被隐藏以不干扰系统libxml2,因此必须对pip有所帮助才能找到它。

用bash:

LDFLAGS=-L`brew --prefix libxml2`/lib CPPFLAGS=-I`brew --prefix libxml2`/include/libxml2 pip install --user lxml

与鱼:

env LDFLAGS=-L(brew --prefix libxml2)/lib CPPFLAGS=-I(brew --prefix libxml2)/include/libxml2 pip install --user lxml

With homebrew, libxml2 is hidden to not interfere with the system libxml2, so pip must be helped a little in order to find it.

With bash:

LDFLAGS=-L`brew --prefix libxml2`/lib CPPFLAGS=-I`brew --prefix libxml2`/include/libxml2 pip install --user lxml

With fish:

env LDFLAGS=-L(brew --prefix libxml2)/lib CPPFLAGS=-I(brew --prefix libxml2)/include/libxml2 pip install --user lxml

回答 11

OSX 10.9.2

sudo env ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future STATIC_DEPS=true pip install lxml

OSX 10.9.2

sudo env ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future STATIC_DEPS=true pip install lxml

回答 12

我尝试了此页面上的所有答案,但没有一个对我有用。我正在运行OS X版本10.9.2

但这绝对有效….就像一个魅力:

ARCHFLAGS = -Wno-error =未使用的命令行参数-将来的硬错误pip install lxml

I tried all the answers on this page, none of them worked for me. I’m running OS X Version 10.9.2

But this definitely works….like a charm:

ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install lxml


回答 13

不幸的是xcode-select --install,由于我已经拥有最新版本,因此不适用于我。

这很奇怪,但是我通过打开XCode并接受条款与条件解决了这个问题。重新运行pip install lxml后未返回任何错误。

Unfortunately xcode-select --install did not work for me as I already had the latest version.

It’s very strange but I solved the issue by opening XCode and accepting the Terms & Conditions. Re-running pip install lxml returned no errors after.


回答 14

从pip(lxml 3.6.4)成功安装后,导入lxml.etree模块时出现错误。

我一直在不停地搜索以将其安装为scrapy的必要条件,并尝试了所有选项,但最终这对我有用(mac osx 10.11 python 2.7):

$ STATIC_DEPS=true sudo easy_install-2.7 "lxml==2.3.5"

较旧的lxml版本似乎可以与etree模块一起使用。

Pip通常可以忽略软件包的指定版本,例如,当您在pip缓存中有较新的版本时,即为easy_install。该'-2.7'选项适用于python版本,如果要安装python 3.x,则忽略此选项。

After successful install from pip (lxml 3.6.4) I was getting an error when importing the lxml.etree module.

I was searching endlessly to install this as a requisite for scrapy, and tried all the options, but finally this worked for me (mac osx 10.11 python 2.7):

$ STATIC_DEPS=true sudo easy_install-2.7 "lxml==2.3.5"

The older version of lxml seem to work with etree module.

Pip can often ignore the specified version of a package, for example when you have the newer version in the pip cache, thus the easy_install. The '-2.7' option is for python version, omit this if you are installing for python 3.x.


回答 15

就我而言,在通过以下方式安装lxml之前,必须关闭Kaspersky Antivirus

pip install lxml

In my case, I must shutdown Kaspersky Antivirus before installing lxml by:

pip install lxml

回答 16

我正在使用OSX 10.9.2,但出现相同的错误。

XCode命令行工具的安装不适用于此特定版本的OSX。

我认为解决此问题的更好方法是使用以下命令进行安装:

$ CPATH=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/include/libxml2 pip install lxml

这类似于jdkoftinoff的修复程序,但不会永久更改系统。

I am using OSX 10.9.2 and I get the same error.

Installation of the XCode command line tools does not help for this particular version of OSX.

I think a better approach to fix this is to install with the following command:

$ CPATH=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/include/libxml2 pip install lxml

This is similar to jdkoftinoff’ fix, but does not alter your system in a permanent way.


回答 17

我遇到了同样的问题,经过几天的工作,我在OS X 10.9.4上使用Python 3.4.1解决了这个问题。

这是我的解决方案,

根据从lxml.de 安装lxml

lxml的macport可用。尝试类似port install py25-lxml的操作

如果您没有MacPort,请从MacPort.org安装它。这很容易。您可能还需要编译器来安装XCode编译工具,使用xcode-select --install

首先,我通过将该端口更新为最新版本sudo port selfupdate

然后我输入sudo port install libxml2,几分钟后,您应该看到libxml2安装成功。可能您可能还需要libxslt安装lxml。要安装libxslt,请使用:sudo port install libxslt

现在,只需键入pip install lxml,它应该可以正常工作。

I met the same question and after days of working I resolved this problem on my OS X 10.9.4, with Python 3.4.1.

Here’s my solution,

According to installing lxml from lxml.de,

A macport of lxml is available. Try something like port install py25-lxml

If you do not have MacPort, install it from MacPort.org. It’s quite easy. You may also need a compiler, to install XCode compiling tools, use xcode-select --install

Firstly I updated my port to the latest version via sudo port selfupdate,

Then I just type sudo port install libxml2 and several minutes later you should see libxml2 installed successfully. Probably you may also need libxslt to install lxml. To install libxslt, use:sudo port install libxslt.

Now, just type pip install lxml, it should work fine.


回答 18

在编译之前,将xmlversion.h的路径添加到您的环境中。

$ set INCLUDE=$INCLUDE:/private/tmp/pip_build_root/lxml/src/lxml/

但是请确保我提供的路径中包含xmlversion.h文件。然后,

$ python setup.py install

before compiling add the path that to xmlversion.h into your environment.

$ set INCLUDE=$INCLUDE:/private/tmp/pip_build_root/lxml/src/lxml/

But make sure the path I’ve provided has the xmlversion.h file located inside. Then,

$ python setup.py install

回答 19

pip没有为我工作。我去了 https://pypi.python.org/pypi/lxml/2.3 并下载了macosx .egg文件:

https://pypi.python.org/packages/2.7/l/lxml/lxml-2.3-py2.7-macosx-10.6-intel.egg#md5=52322e4698d68800c6b6aedb0dbe5f34

然后使用命令行easy_install安装.egg文件。

pip did not work for me. I went to https://pypi.python.org/pypi/lxml/2.3 and downloaded the macosx .egg file:

https://pypi.python.org/packages/2.7/l/lxml/lxml-2.3-py2.7-macosx-10.6-intel.egg#md5=52322e4698d68800c6b6aedb0dbe5f34

Then used command line easy_install to install the .egg file.


回答 20

这篇文章链接到一个适用于我的解决方案,在Mac OS X 10.9上适用于 Python3,lxml和“未找到符号:_lzma_auto_decoder”

hth


回答 21

在头发多撕裂和咬牙切齿之后,我用pip卸载了xcode并运行:

easy_install lxml

一切都很好。

After much tearing of the hair and gnashing of the teeth, I uninstalled xcode with pip and ran:

easy_install lxml

And all was well.


回答 22

尝试:

% STATIC_DEPS=true pip install lxml

要么:

% STATIC_DEPS=true sudo pip install lxml

有用!

Try:

% STATIC_DEPS=true pip install lxml

Or:

% STATIC_DEPS=true sudo pip install lxml

It works!


如何在Mac OS X 10.6.4上卸载Python 2.7?

问题:如何在Mac OS X 10.6.4上卸载Python 2.7?

我想从Mac OS X 10.6.4中完全删除Python 2.7。我设法PATH通过还原删除了变量中的条目.bash_profile。但我也想删除所有由python 2.7安装包安装的目录,文件,符号链接和条目。我从http://www.python.org/获得了安装包。我需要删除哪些目录/文件/配置文件条目?某处有清单吗?

I want to completely remove Python 2.7 from my Mac OS X 10.6.4. I managed to remove the entry from the PATH variable by reverting my .bash_profile. But I also want to remove all directories, files, symlinks, and entries that got installed by the Python 2.7 install package. I’ve got the install package from http://www.python.org/. What directories/files/configuration file entries do I need to remove? Is there a list somewhere?


回答 0

不要试图删除任何苹果公司提供的系统的Python这是在/System/Library/usr/bin,因为这可能会破坏你的整个操作系统。


注意: 以下列出的步骤不会影响Apple提供的系统Python 2.7;请参阅附录A。他们只会删除第三方Python框架,例如python.org安装程序安装的框架。


完整列表在此处记录。基本上,您需要做的是:

  1. 删除第三方Python 2.7框架

    sudo rm -rf /Library/Frameworks/Python.framework/Versions/2.7
  2. 删除Python 2.7应用程序目录

    sudo rm -rf "/Applications/Python 2.7"
  3. 在中删除/usr/local/bin指向此Python版本的符号链接。看到他们使用

    ls -l /usr/local/bin | grep '../Library/Frameworks/Python.framework/Versions/2.7' 

    然后运行以下命令删除所有链接:

    cd /usr/local/bin/
    ls -l /usr/local/bin | grep '../Library/Frameworks/Python.framework/Versions/2.7' | awk '{print $9}' | tr -d @ | xargs rm
  4. 如有必要,请编辑您的外壳配置文件,以删除添加/Library/Frameworks/Python.framework/Versions/2.7到您的PATH环境文件中的操作。根据您所使用的shell,任何下列文件可能已被修改: ~/.bash_login~/.bash_profile~/.cshrc~/.profile~/.tcshrc,和/或~/.zprofile

Do not attempt to remove any Apple-supplied system Python which are in /System/Library and /usr/bin, as this may break your whole operating system.


NOTE: The steps listed below do not affect the Apple-supplied system Python 2.7; they only remove a third-party Python framework, like those installed by python.org installers.


The complete list is documented here. Basically, all you need to do is the following:

  1. Remove the third-party Python 2.7 framework

    sudo rm -rf /Library/Frameworks/Python.framework/Versions/2.7
    
  2. Remove the Python 2.7 applications directory

    sudo rm -rf "/Applications/Python 2.7"
    
  3. Remove the symbolic links, in /usr/local/bin, that point to this Python version. See them using

    ls -l /usr/local/bin | grep '../Library/Frameworks/Python.framework/Versions/2.7' 
    

    and then run the following command to remove all the links:

    cd /usr/local/bin/
    ls -l /usr/local/bin | grep '../Library/Frameworks/Python.framework/Versions/2.7' | awk '{print $9}' | tr -d @ | xargs rm
    
  4. If necessary, edit your shell profile file(s) to remove adding /Library/Frameworks/Python.framework/Versions/2.7 to your PATH environment file. Depending on which shell you use, any of the following files may have been modified: ~/.bash_login, ~/.bash_profile, ~/.cshrc, ~/.profile, ~/.tcshrc, and/or ~/.zprofile.


回答 1

这个作品:

cd /usr/local/bin/
ls -l /usr/local/bin | grep '../Library/Frameworks/Python.framework/Versions/2.7' | awk '{print $9}' | tr -d @ | xargs rm

描述:列出所有链接,删除@字符,然后删除它们。

This one works:

cd /usr/local/bin/
ls -l /usr/local/bin | grep '../Library/Frameworks/Python.framework/Versions/2.7' | awk '{print $9}' | tr -d @ | xargs rm

Description: It list all the links, removes @ character and then removes them.


回答 2

如果使用PKG安装程序安装了它,则可以执行以下操作:

pkgutil --pkgs

或更好:

pkgutil --pkgs | grep org.python.Python

这将输出类似:

org.python.Python.PythonApplications-2.7
org.python.Python.PythonDocumentation-2.7
org.python.Python.PythonFramework-2.7
org.python.Python.PythonProfileChanges-2.7
org.python.Python.PythonUnixTools-2.7

您现在可以选择要取消链接(删除)的软件包。

这是取消链接文档:

 --unlink package-id
             Unlinks (removes) each file referenced by package-id. WARNING: This command makes no attempt to perform reference counting or dependency analy-
             sis. It can easily remove files required by your system. It may include unexpected files due to package tainting. Use the --files command first
             to double check.

在我的示例中,您将输入

pkgutil --unlink org.python.Python.PythonApplications-2.7
pkgutil --unlink org.python.Python.PythonDocumentation-2.7
pkgutil --unlink org.python.Python.PythonFramework-2.7
pkgutil --unlink org.python.Python.PythonProfileChanges-2.7
pkgutil --unlink org.python.Python.PythonUnixTools-2.7

或一行:

pkgutil --pkgs | grep org.python.Python | xargs -L1 pkgutil -f --unlink

重要提示:–unlink从Lion(从2014年第一季度开始,包括Lion,Mountain Lion和Mavericks)不再可用。如果涉及此说明的任何人都尝试将其与狮子一起使用,则应尝试改编本文所讲的内容:https : //wincent.com/wiki/Uninstalling_packages_(.pkg_files)_on_Mac_OS_X

If you installed it using the PKG installer, you can do:

pkgutil --pkgs

or better:

pkgutil --pkgs | grep org.python.Python

which will output something like:

org.python.Python.PythonApplications-2.7
org.python.Python.PythonDocumentation-2.7
org.python.Python.PythonFramework-2.7
org.python.Python.PythonProfileChanges-2.7
org.python.Python.PythonUnixTools-2.7

you can now select which packages you will unlink (remove).

This is the unlink documentation:

 --unlink package-id
             Unlinks (removes) each file referenced by package-id. WARNING: This command makes no attempt to perform reference counting or dependency analy-
             sis. It can easily remove files required by your system. It may include unexpected files due to package tainting. Use the --files command first
             to double check.

In my example you will type

pkgutil --unlink org.python.Python.PythonApplications-2.7
pkgutil --unlink org.python.Python.PythonDocumentation-2.7
pkgutil --unlink org.python.Python.PythonFramework-2.7
pkgutil --unlink org.python.Python.PythonProfileChanges-2.7
pkgutil --unlink org.python.Python.PythonUnixTools-2.7

or in one single line:

pkgutil --pkgs | grep org.python.Python | xargs -L1 pkgutil -f --unlink

Important: –unlink is not available anymore starting with Lion (as of Q1`2014 that would include Lion, Mountain Lion, and Mavericks). If anyone that comes to this instructions try to use it with lion, should try instead to adapt it with what this post is saying: https://wincent.com/wiki/Uninstalling_packages_(.pkg_files)_on_Mac_OS_X


回答 3

尝试使用卸载Python

brew uninstall python

不会删除本机安装了Python,而是版本安装brew

Trying to uninstall Python with

brew uninstall python

will not remove the natively installed Python but rather the version installed with brew.


回答 4

关于删除符号链接,我发现这很有用。

find /usr/local/bin -lname '../../../Library/Frameworks/Python.framework/Versions/2.7/*' -delete

In regards to deleting the symbolic links, I found this to be useful.

find /usr/local/bin -lname '../../../Library/Frameworks/Python.framework/Versions/2.7/*' -delete

回答 5

创建符号链接到最新版本

 ln -s -f /usr/local/bin/python3.8 /usr/local/bin/python

关闭并打开一个新终端

并尝试

 python --version

Create the symlink to latest version

 ln -s -f /usr/local/bin/python3.8 /usr/local/bin/python

Close and open a new terminal

and try

 python --version

回答 6

无需卸载旧的python版本。

只需安装新版本,说python-3.3.2-macosx10.6.dmg并将python的软链接更改为新安装的python3.3

使用以下命令检查默认python和python3.3的路径

“哪个python”和“哪个python3.3”

然后删除python的现有软链接并将其指向python3.3

No need to uninstall old python versions.

Just install new version say python-3.3.2-macosx10.6.dmg and change the soft link of python to newly installed python3.3

Check the path of default python and python3.3 with following commands

“which python” and “which python3.3”

then delete existing soft link of python and point it to python3.3


回答 7

OnurGüzel在他的博客文章“从OS X卸载Python包”中提供了解决方案。

您应该在终端中键入以下命令:

  1. sudo rm -rf /Library/Frameworks/Python.framework
  2. cd /usr/local/bin
  3. ls -l . | grep '../Library/Frameworks/Python.framework' | awk '{print $9}' | xargs sudo rm
  4. sudo rm -rf "/Applications/Python x.y"

    其中命令xy是安装的Python版本。根据您的问题,应该是2.7。

用Onur的话来说:

警告:此命令将删除与软件包一起安装的所有Python版本。系统提供的Python不会受到影响。

如果您从python.org安装了多个Python版本,请再次运行第四个命令,为每个要卸载的Python版本更改“ xy”。

Onur Güzel provides the solution in his blog post, “Uninstall Python Package from OS X.

You should type the following commands into the terminal:

  1. sudo rm -rf /Library/Frameworks/Python.framework
  2. cd /usr/local/bin
  3. ls -l . | grep '../Library/Frameworks/Python.framework' | awk '{print $9}' | xargs sudo rm
  4. sudo rm -rf "/Applications/Python x.y"

    where command x.y is the version of Python installed. According to your question, it should be 2.7.

In Onur’s words:

WARNING: This commands will remove all Python versions installed with packages. Python provided from the system will not be affected.

If you have more than 1 Python version installed from python.org, then run the fourth command again, changing “x.y” for each version of Python that is to be uninstalled.


回答 8

注意如果使用Homebrew安装了Python,则可以按照以下步骤操作,否则请寻找其他解决方案!


要卸载使用Homebrew安装的Python 2.7.10,可以简单地发出以下命令:

brew uninstall python

同样,如果要卸载Python 3(使用Homebrew安装),请执行以下操作:

brew uninstall --force python3

Note: If you installed Python using Homebrew, then you can follow the following steps, otherwise look for another solution!


To uninstall Python 2.7.10 which you installed using Homebrew, then you can simply issue the following command:

brew uninstall python

Similarly, if you want to uninstall Python 3 (which you installed using Homebrew):

brew uninstall --force python3

回答 9

无需卸载它或使用符号链接发疯,只需使用即可alias。升级到python 3.7.1时,我遇到了同样的问题。
只需使用安装新的python版本,brew install python然后在.bash_profile创建的别名中指向新的python版本即可;这样:alias python="/usr/local/bin/python3"然后保存并运行source ~/.bash_profile
做完了

No need to uninstall it or going crazy with symbolic links, just use an alias. I faced the same problem when upgrading to python 3.7.1.
Just install the new python version using brew install python then in your .bash_profile create an alias pointing to the new python version; like this: alias python="/usr/local/bin/python3" then save and run source ~/.bash_profile.
Done.


回答 10

如果您正在考虑手动删除Apple的默认Python 2.7,建议您立即执行以下操作:看起来Apple很快会为您完成此操作:

OSX 10.15 Catalina中不推荐使用Python 2.7

Catalina中不推荐使用Python 2.7-以及Ruby和Perl :(跳至“ 脚本语言运行时 ”>“ 不推荐使用 ”部分)

https://developer.apple.com/documentation/macos_release_notes/macos_catalina_10_15_release_notes

苹果将​​在OSX 10.16中删除Python 2.7

确实,如果您什么都不做,那么根据OS X版本10.16 的Mac Observer所述,Python 2.7将从您的系统中消失:

https://www.macobserver.com/analysis/macos-catalina-deprecates-unix-scripting-languages/

鉴于这一启示,我建议最好的做法是什么也不做,等待苹果为您清除。由于Apple即将为您删除它,因此似乎不值得尝试修改您的Python环境。

注意:我看到这个问题专门与OSX v 10.6.4有关,但是对于所有有兴趣从其系统中删除Python 2.7的OSX人士,无论他们运行的是哪个版本,该问题似乎都已成为一个关键点。

If you’re thinking about manually removing Apple’s default Python 2.7, I’d suggest you hang-fire and do-noting: Looks like Apple will very shortly do it for you:

Python 2.7 Deprecated in OSX 10.15 Catalina

Python 2.7- as well as Ruby & Perl- are deprecated in Catalina: (skip to section “Scripting Language Runtimes” > “Deprecations“)

https://developer.apple.com/documentation/macos_release_notes/macos_catalina_10_15_release_notes

Apple To Remove Python 2.7 in OSX 10.16

Indeed, if you do nothing at all, according to The Mac Observer, by OSX version 10.16, Python 2.7 will disappear from your system:

https://www.macobserver.com/analysis/macos-catalina-deprecates-unix-scripting-languages/

Given this revelation, I’d suggest the best course of action is do nothing and wait for Apple to wipe it for you. As Apple is imminently about to remove it for you, doesn’t seem worth the risk of tinkering with your Python environment.

NOTE: I see the question relates specifically to OSX v 10.6.4, but it appears this question has become a pivot-point for all OSX folks interested in removing Python 2.7 from their systems, whatever version they’re running.


如何在OS X上将Python的默认版本设置为3.x?

问题:如何在OS X上将Python的默认版本设置为3.x?

我正在运行Mountain Lion,而基本的默认Python版本是2.7。我下载了Python 3.3,并希望将其设置为默认值。

目前:

$ python
    version 2.7.5
$ python3.3
    version 3.3

如何设置它,以便每次运行$ python时都能打开3.3?

I’m running Mountain Lion and the basic default Python version is 2.7. I downloaded Python 3.3 and want to set it as default.

Currently:

$ python
    version 2.7.5
$ python3.3
    version 3.3

How do I set it so that every time I run $ python it opens 3.3?


回答 0

在系统范围内更改默认python可执行文件的版本可能会破坏某些依赖python2的应用程序。

但是,您可以在大多数外壳程序中为命令加上别名,因为macOS中的默认外壳程序(10.14及以下版本中的bash; 10.15中的zsh)具有相似的语法。您可以在您的中放置别名python =’python3′ ~/.profile,然后~/.profile在您~/.bash_profile和/或您的源代码中~/.zsh_profile输入以下内容:

[ -e ~/.profile ] && . ~/.profile

这样,您的别名将可在所有shell中使用。

这样,python命令现在将被调用python3。如果您想偶尔调用“原始” python(指python2),则可以使用command python,这将使别名保持不变,并且适用于所有shell。

如果您更频繁地启动解释器(我愿意),则总是可以创建更多别名来添加,即:

alias 2='python2'
alias 3='python3'

提示:对于脚本,而不是使用shebang之类的方法:

#!/usr/bin/env python

采用:

#!/usr/bin/env python3

这样,系统将使用python3运行python 可执行文件

Changing the default python executable’s version system-wide could break some applications that depend on python2.

However, you can alias the commands in most shells, Since the default shells in macOS (bash in 10.14 and below; zsh in 10.15) share a similar syntax. You could put alias python=’python3′ in your ~/.profile, and then source ~/.profile in your ~/.bash_profile and/or your~/.zsh_profile with a line like:

[ -e ~/.profile ] && . ~/.profile

This way, your alias will work across shells.

With this, python command now invokes python3. If you want to invoke the “original” python (that refers to python2) on occasion, you can use command python, which will leaving the alias untouched, and works in all shells.

If you launch interpreters more often (I do), you can always create more aliases to add as well, i.e.:

alias 2='python2'
alias 3='python3'

Tip: For scripts, instead of using a shebang like:

#!/usr/bin/env python

use:

#!/usr/bin/env python3

This way, the system will use python3 for running python executables.


回答 1

您可以通过符号链接来解决。

unlink /usr/local/bin/python
ln -s /usr/local/bin/python3.3 /usr/local/bin/python

You can solve it by symbolic link.

unlink /usr/local/bin/python
ln -s /usr/local/bin/python3.3 /usr/local/bin/python

回答 2

打开〜/ .bash_profile文件。

vi ~/.bash_profile

然后按如下所示放置别名:

alias python='python3'

现在保存文件,然后运行〜/ .bash_profile文件。

source ~/.bash_profile

恭喜!!!现在,您可以通过键入python使用python3 。

python --version

的Python 3.7.3

Open ~/.bash_profile file.

vi ~/.bash_profile

Then put the alias as follows:

alias python='python3'

Now save the file and then run the ~/.bash_profile file.

source ~/.bash_profile

Congratulation !!! Now, you can use python3 by typing python.

python --version

Python 3.7.3


回答 3

转到终端类型:

alias python=python3.x

这会将默认python设置为python3.x

Go to terminal type:

alias python=python3.x

This will setup default python as python3.x


回答 4

以下为我工作

cd /usr/local/bin
mv python python.old
ln -s python3 python

The following worked for me

cd /usr/local/bin
mv python python.old
ln -s python3 python

回答 5

我在这个游戏上有点晚了,但是我认为我应该发布更新的答案,因为我自己才遇到这个问题。请注意,这仅适用于基于Mac的设置(我没有在Windows或任何版本的Linux上尝试过)。

最简单的方法是通过Brew安装Python 。如果您未安装brew,则需要先执行该操作。安装完成后,在终端上执行以下操作:

brew install python

这将安装Python3。安装后,运行以下命令:

ls -l /usr/local/bin/python*

您将看到brew创建的所有安装到其Python安装的链接。它看起来像这样:

lrwxr-xr-x  1 username  admin  36 Oct  1 13:35 /usr/local/bin/python3@ -> ../Cellar/python/3.7.4_1/bin/python3
lrwxr-xr-x  1 username  admin  43 Oct  1 13:35 /usr/local/bin/python3-config@ -> ../Cellar/python/3.7.4_1/bin/python3-config
lrwxr-xr-x  1 username  admin  38 Oct  1 13:35 /usr/local/bin/python3.7@ -> ../Cellar/python/3.7.4_1/bin/python3.7
lrwxr-xr-x  1 username  admin  45 Oct  1 13:35 /usr/local/bin/python3.7-config@ -> ../Cellar/python/3.7.4_1/bin/python3.7-config
lrwxr-xr-x  1 username  admin  39 Oct  1 13:35 /usr/local/bin/python3.7m@ -> ../Cellar/python/3.7.4_1/bin/python3.7m
lrwxr-xr-x  1 username  admin  46 Oct  1 13:35 /usr/local/bin/python3.7m-config@ -> ../Cellar/python/3.7.4_1/bin/python3.7m-config

此示例的第一行显示了python3符号链接。要将其设置为默认python符号链接,请运行以下命令:

ln -s -f /usr/local/bin/python3 /usr/local/bin/python

设置后,您可以执行以下操作:

which python

它应该显示:

/usr/local/bin/python

您将必须重新加载当前的终端shell,才能在该shell中使用新的符号链接,但是,所有新打开的shell会话将(应该)自动使用它。要对此进行测试,请打开一个新的终端外壳并运行以下命令:

python --version

I’m a little late to the game on this one, but I thought I should post an updated answer since I just encountered this issue for myself. Please note that this will only apply to a Mac-based setup (I haven’t tried it with Windows or any flavor of Linux).

The simplest way to get this working is to install Python via Brew. If you don’t have brew installed, you will need to do that first. Once installed, do the following in at the terminal:

brew install python

This will install Python 3. After it’s installed, run this:

ls -l /usr/local/bin/python*

You will see all of the links created by brew to its Python install. It will look something like this:

lrwxr-xr-x  1 username  admin  36 Oct  1 13:35 /usr/local/bin/python3@ -> ../Cellar/python/3.7.4_1/bin/python3
lrwxr-xr-x  1 username  admin  43 Oct  1 13:35 /usr/local/bin/python3-config@ -> ../Cellar/python/3.7.4_1/bin/python3-config
lrwxr-xr-x  1 username  admin  38 Oct  1 13:35 /usr/local/bin/python3.7@ -> ../Cellar/python/3.7.4_1/bin/python3.7
lrwxr-xr-x  1 username  admin  45 Oct  1 13:35 /usr/local/bin/python3.7-config@ -> ../Cellar/python/3.7.4_1/bin/python3.7-config
lrwxr-xr-x  1 username  admin  39 Oct  1 13:35 /usr/local/bin/python3.7m@ -> ../Cellar/python/3.7.4_1/bin/python3.7m
lrwxr-xr-x  1 username  admin  46 Oct  1 13:35 /usr/local/bin/python3.7m-config@ -> ../Cellar/python/3.7.4_1/bin/python3.7m-config

The first row in this example shows the python3 symlink. To set it as the default python symlink run the following:

ln -s -f /usr/local/bin/python3 /usr/local/bin/python

Once set, you can do:

which python

and it should show:

/usr/local/bin/python

You will have to reload your current terminal shell for it to use the new symlink in that shell, however, all newly opened shell sessions will (should) automatically use it. To test this, open a new terminal shell and run the following:

python --version

回答 6

转到“应用程序”,进入“ Python”文件夹,应该有一个名为“ Update Shell Profile.command”或类似名称的bash脚本。运行该脚本,它应该这样做。

更新:看来您不应该更新它:如何更改默认python版本?

Go to ‘Applications’, enter ‘Python’ folder, there should be a bash script called ‘Update Shell Profile.command’ or similar. Run that script and it should do it.

Update: It looks like you should not update it: how to change default python version?


回答 7

这对我有用。我添加了别名并重新启动了终端

alias python=/usr/local/bin/python3

This worked for me. I added alias and restarted my terminal:

alias python=/usr/local/bin/python3

回答 8

我相信大多数登陆这里的人都在使用ZSH thorugh iterm或其他工具,这为您带来了答案

您必须改为添加/修改命令~/.zshrc

I believe most of people landed here are using ZSH thorugh iterm or whatever, and that brings you to this answer.

You have to add/modify your commands in ~/.zshrc instead.


回答 9

我不确定在OS X上是否可用,但是在Linux上我会使用该module命令。 看这里

正确设置modulefile,然后将以下内容添加到rc文件中(例如〜/ .bashrc):

module load python3.3

这样一来,登录时即可根据需要切换路径,而不会影响任何系统默认值。

I’m not sure if this is available on OS X, but on linux I would make use of the module command. See here.

Set up the modulefile correctly, then add something like this to your rc file (e.g. ~/.bashrc):

module load python3.3

This will make it so that your paths get switched around as required when you log in without impacting any system defaults.


回答 10

我认为安装python时会将导出路径语句放入〜/ .bash_profile文件中。因此,如果您不再打算使用Python 2,则可以从那里删除该语句。如上所述的别名也是一种很好的方法。

这是从〜/ .bash_profile中删除引用的方法-vim ./.bash_profile-删除引用(也类似:export PATH =“ / Users / bla / anaconda:$ PATH”)-保存并退出-源./ .bash_profile保存更改

I think when you install python it puts export path statements into your ~/.bash_profile file. So if you do not intend to use Python 2 anymore you can just remove that statement from there. Alias as stated above is also a great way to do it.

Here is how to remove the reference from ~/.bash_profile – vim ./.bash_profile – remove the reference (AKA something like: export PATH=”/Users/bla/anaconda:$PATH”) – save and exit – source ./.bash_profile to save the changes


回答 11

$ sudo ln -s -f $(which python3) $(which python)

完成。

$ sudo ln -s -f $(which python3) $(which python)

done.


回答 12

在Mac上将Python 3设置为默认的正确和错误的方法

在本文中,作者讨论了设置默认python的三种方法:

  1. 什么不该做。
  2. 我们可以做(但也不应该)。
  3. 我们应该做什么!

所有这些方式都有效。您决定哪个更好。

The RIGHT and WRONG way to set Python 3 as default on a Mac

In this article author discuss three ways of setting default python:

  1. What NOT to do.
  2. What we COULD do (but also shouldn’t).
  3. What we SHOULD do!

All these ways are working. You decide which is better.


回答 13

如果virtualenvwrapper使用which virtualenvwrapper.sh,则可以使用进行定位,然后使用vim或任何其他编辑器将其打开,然后更改以下内容

# Locate the global Python where virtualenvwrapper is installed.
if [ "${VIRTUALENVWRAPPER_PYTHON:-}" = "" ]
then
    VIRTUALENVWRAPPER_PYTHON="$(command \which python)"
fi

将行更改VIRTUALENVWRAPPER_PYTHON="$(command \which python)"VIRTUALENVWRAPPER_PYTHON="$(command \which python3)"

If you are using a virtualenvwrapper, you can just locate it using which virtualenvwrapper.sh, then open it using vim or any other editor then change the following

# Locate the global Python where virtualenvwrapper is installed.
if [ "${VIRTUALENVWRAPPER_PYTHON:-}" = "" ]
then
    VIRTUALENVWRAPPER_PYTHON="$(command \which python)"
fi

Change the line VIRTUALENVWRAPPER_PYTHON="$(command \which python)" to VIRTUALENVWRAPPER_PYTHON="$(command \which python3)".


回答 14

对我来说,解决方案是使用PyCharm并将默认的python版本设置为我需要使用的版本。

安装PyCharm并转到文件==>新项目的首选项,然后为项目选择所需的解释器,在这种情况下为python 3.3

For me the solution was using PyCharm and setting the default python version to the the one that i need to work with.

install PyCharm and go to file ==> preferences for new project, then choose the interpreter you want for your projects, in this case python 3.3


回答 15

如果您使用macports,则不需要使用别名或环境变量,只需使用macports已经提供的方法,此问答将对此进行说明:

作法:Macports选择python

TL; DR:

sudo port select --set python python27

If you use macports, you do not need to play with aliases or environment variables, just use the the method macports already offers, explained by this Q&A:

How to: Macports select python

TL;DR:

sudo port select --set python python27

回答 16

如果您使用的是Macports,则有一种更简单的方法:

跑:

port install python37

安装后,设置默认值:

sudo port select --set python python37

sudo port select --set python3 python37

重新启动您的cmd窗口,完成。

If you are using macports, that has a easier way to do:

run:

port install python37

after install, set default:

sudo port select --set python python37

sudo port select --set python3 python37

restart your cmd window, finished.


回答 17

好吧…有点老了。但是仍然值得一个好的答案。

优点之一是您不想触摸Mac上的默认Python。

通过Homebrew或其他方式安装所需的任何Python版本,然后在virtualenv中使用它。Virtualenv通常被认为是胡扯,但还是比在系统范围内更改python版本(macOS可能会保护自己免受此类操作)或用户范围,bash范围……好得多。只需忘记默认的Python。使用venv这样的游乐场是您的操作系统最感谢的事情。

例如,这种情况是,许多现代Linux发行版都摆脱了现成安装的Python2的安装,仅在系统中保留了Python3。但是每次您尝试使用python2作为依赖项安装旧版本时…希望您理解我的意思。一个好的开发者不在乎。好的开发人员可以使用他们想要的python版本创建干净的游乐场。

Well… It’s kinda old. But still deserves a good answer.

And the good one is You Don’t Wanna Touch The Default Python On Mac.

Install any Python version you need via Homebrew or whatever and use it in virtualenv. Virtualenv is often considered to be something crap-like, but it’s still way, wayyyy better than changing python version system-wide (macOS is likely to protect itself from such actions) or user-wide, bash-wide… whatever. Just forget about the default Python. Using playgrounds like venv is what your OS will be most, very most grateful for.

The case is, for example, many modern Linux distributions get rid of Python2 installed out-of-the-box, leaving only Python3 in the system. But everytime you try to install something old with python2 as a dependency… hope you understand what I mean. A good developer doesn’t care. Good developers create clean playgrounds with python version they desire.


回答 18

Mac用户只需要在终端上运行以下代码

brew switch python 3.x.x

3.xx应该是新的python版本。

这将更新所有系统链接。

Mac users just need to run the following code on terminal

brew switch python 3.x.x

3.x.x should be the new python version.

This will update all the system links.


回答 19

建议将python别名为python3会导致设置python版本的虚拟环境出现问题(例如:pyenv)。使用pyenv,您可以像下面这样全局设置版本:

pyenv global 3.8.2

然后在任何特定项目中,您都可以创建一个.python-version文件,其中包含python版本:

pyenv local 2.7.1

我认为这是在系统上管理多个版本的python的最佳方法。

Suggestions to alias python to python3 will cause problems with virtual environments that set the version of python (eg: pyenv). With pyenv, you can set the version globally like so:

pyenv global 3.8.2

and then in any specific project, you can create a .python-version file which has the python version inside of it:

pyenv local 2.7.1

This is the best way to manage multiple versions of python on a system in my opinion.


如何确定我的python shell是在OS X上以32位还是64位模式执行?

问题:如何确定我的python shell是在OS X上以32位还是64位模式执行?

我需要一种方法,从外壳程序中告诉外壳程序处于哪种模式。

我尝试查看平台模块,但似乎只告诉您“有关可执行文件所用的位体系结构和链接格式”的信息:尽管二进制文件编译为64位(我在OS X 10.6上运行),所以即使我使用此处介绍的方法强制使用32位模式,它似乎总是报告64 位。

I need a way to tell what mode the shell is in from within the shell.

I’ve tried looking at the platform module but it seems only to tell you about “about the bit architecture and the linkage format used for the executable”: the binary is compiled as 64bit though (I’m running on OS X 10.6) so it seems to always report 64bit even though I’m using the methods described here to force 32bit mode).


回答 0

一种方法是看sys.maxsize作为记录在这里

$ python-32 -c 'import sys;print("%x" % sys.maxsize, sys.maxsize > 2**32)'
('7fffffff', False)
$ python-64 -c 'import sys;print("%x" % sys.maxsize, sys.maxsize > 2**32)'
('7fffffffffffffff', True)

sys.maxsize是Python 2.6中引入的。如果您需要针对较旧系统的测试,则此稍微复杂一些的测试应适用于所有Python 2和3版本:

$ python-32 -c 'import struct;print( 8 * struct.calcsize("P"))'
32
$ python-64 -c 'import struct;print( 8 * struct.calcsize("P"))'
64

顺便说一句,您可能会想使用platform.architecture()它。不幸的是,其结果并不总是可靠的,特别是在OS X通用二进制文件的情况下

$ arch -x86_64 /usr/bin/python2.6 -c 'import sys,platform; print platform.architecture()[0], sys.maxsize > 2**32'
64bit True
$ arch -i386 /usr/bin/python2.6 -c 'import sys,platform; print platform.architecture()[0], sys.maxsize > 2**32'
64bit False

One way is to look at sys.maxsize as documented here:

$ python-32 -c 'import sys;print("%x" % sys.maxsize, sys.maxsize > 2**32)'
('7fffffff', False)
$ python-64 -c 'import sys;print("%x" % sys.maxsize, sys.maxsize > 2**32)'
('7fffffffffffffff', True)

sys.maxsize was introduced in Python 2.6. If you need a test for older systems, this slightly more complicated test should work on all Python 2 and 3 releases:

$ python-32 -c 'import struct;print( 8 * struct.calcsize("P"))'
32
$ python-64 -c 'import struct;print( 8 * struct.calcsize("P"))'
64

BTW, you might be tempted to use platform.architecture() for this. Unfortunately, its results are not always reliable, particularly in the case of OS X universal binaries.

$ arch -x86_64 /usr/bin/python2.6 -c 'import sys,platform; print platform.architecture()[0], sys.maxsize > 2**32'
64bit True
$ arch -i386 /usr/bin/python2.6 -c 'import sys,platform; print platform.architecture()[0], sys.maxsize > 2**32'
64bit False

回答 1

在终端/命令行中启动Python解释器时,您可能还会看到类似以下的行:

Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32

其中[MSC v.1500 64 bit (AMD64)]表示64位Python。适用于我的特定设置。

When starting the Python interpreter in the terminal/command line you may also see a line like:

Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32

Where [MSC v.1500 64 bit (AMD64)] means 64-bit Python. Works for my particular setup.


回答 2

基本上是马修·马歇尔(Matthew Marshall)回答的变体(带有来自标准库的结构):

import struct
print struct.calcsize("P") * 8

Basically a variant on Matthew Marshall’s answer (with struct from the std.library):

import struct
print struct.calcsize("P") * 8

回答 3

尝试使用ctypes获得void指针的大小:

import ctypes
print ctypes.sizeof(ctypes.c_voidp)

对于32位将是4,对于64位将是8。

Try using ctypes to get the size of a void pointer:

import ctypes
print ctypes.sizeof(ctypes.c_voidp)

It’ll be 4 for 32 bit or 8 for 64 bit.


回答 4

打开python控制台:

import platform
platform.architecture()[0]

它应根据您的平台显示“ 64bit”或“ 32bit”。

或者对于OS X二进制文件):

import sys
sys.maxsize > 2**32 
# it should display True in case of 64bit and False in case of 32bit

Open python console:

import platform
platform.architecture()[0]

it should display the ’64bit’ or ’32bit’ according to your platform.

Alternatively( in case of OS X binaries ):

import sys
sys.maxsize > 2**32 
# it should display True in case of 64bit and False in case of 32bit

回答 5

对于非编程解决方案,请查看活动监视器。它将64位进程的体系结构列为“ Intel(64位)”。

For a non-programmatic solution, look in the Activity Monitor. It lists the architecture of 64-bit processes as “Intel (64-bit)”.


回答 6

在我的Centos Linux系统上,我做了以下工作:

1)启动Python解释器(我使用的是2.6.6)
2)运行以下代码:

import platform
print(platform.architecture())

它给了我

(64bit, 'ELF')

On my Centos Linux system I did the following:

1) Started the Python interpreter (I’m using 2.6.6)
2) Ran the following code:

import platform
print(platform.architecture())

and it gave me

(64bit, 'ELF')

回答 7

platform.architecture() 笔记说:

注意:在Mac OS X(可能还有其他平台)上,可执行文件可能是包含多种体系结构的通用文件。

为了获得当前解释器的“ 64位”,查询sys.maxsize属性更加可靠:

import sys
is_64bits = sys.maxsize > 2**32

platform.architecture() notes say:

Note: On Mac OS X (and perhaps other platforms), executable files may be universal files containing multiple architectures.

To get at the “64-bitness” of the current interpreter, it is more reliable to query the sys.maxsize attribute:

import sys
is_64bits = sys.maxsize > 2**32

回答 8

分组一切…

考虑到:

  • 询问OSX的问题(我有一个旧的(且已破解的)VM,带有一个古老的Python版本)
  • 我的主要环境是Win
  • 我在Win上仅安装了32位版本(并且在Lnx上构建了一个“残缺的” 版本

我将使用Python 3Python 2在所有3个平台上进行示例。

  1. 检查[Python 3.Docs]:sys。maxsize值-与0x1000000002 ** 32)比较:对于64位,较大,对于32 ,较小:
    • OSX 9 x64
      • Python 2.7.10 x64
        >>> import sys
        >>> "Python {0:s} on {1:s}".format(sys.version, sys.platform)
        'Python 2.7.10 (default, Oct 14 2015, 05:51:29) \n[GCC 4.8.2] on darwin'
        >>> hex(sys.maxsize), sys.maxsize > 0x100000000
        ('0x7fffffffffffffff', True)
    • Ubuntu 16 x64
      • Python 3.5.2 x64
        >>> import sys
        >>> "Python {0:s} on {1:s}".format(sys.version, sys.platform)
        'Python 3.5.2 (default, Nov 23 2017, 16:37:01) \n[GCC 5.4.0 20160609] on linux'
        >>> hex(sys.maxsize), sys.maxsize > 0x100000000
        ('0x7fffffffffffffff', True)
      • Python 3.6.4 x86
        >>> import sys
        >>> "Python {0:s} on {1:s}".format(sys.version, sys.platform)
        'Python 3.6.4 (default, Apr 25 2018, 23:55:56) \n[GCC 5.4.0 20160609] on linux'
        >>> hex(sys.maxsize), sys.maxsize > 0x100000000
        ('0x7fffffff', False)
    • 赢10 x64
      • Python 3.5.4 x64
        >>> import sys
        >>> "Python {0:s} on {1:s}".format(sys.version, sys.platform)
        'Python 3.5.4 (v3.5.4:3f56838, Aug  8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] on win32'
        >>> hex(sys.maxsize), sys.maxsize > 0x100000000
        ('0x7fffffffffffffff', True)
      • Python 3.6.2 x86
        >>> import sys
        >>> "Python {0:s} on {1:s}".format(sys.version, sys.platform)
        'Python 3.6.2 (v3.6.2:5fd33b5, Jul  8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32'
        >>> hex(sys.maxsize), sys.maxsize > 0x100000000
        ('0x7fffffff', False)


  1. 使用[Python 3.Docs]:结构。calcsizeformat确定由(指针)格式产生的对象大小。换句话说,确定指针大小(sizeof(void*)):
    • OSX 9 x64
      • Python 2.7.10 x64
        >>> import struct
        >>> struct.calcsize("P") * 8
        64
    • Ubuntu 16 x64
      • Python 3.5.2 x64
        >>> import struct
        >>> struct.calcsize("P") * 8
        64
      • Python 3.6.4 x86
        >>> import struct
        >>> struct.calcsize("P") * 8
        32
    • 赢10 x64
      • Python 3.5.4 x64
        >>> import struct
        >>> struct.calcsize("P") * 8
        64
      • Python 3.6.2 x86
        >>> import struct
        >>> struct.calcsize("P") * 8
        32


  1. 使用[Python 3.Docs]:ctypes-Python的外部函数库。它还归结为确定指针(sizeof(void*))的大小。注意,ctypes使用#2。(不一定要完成此任务),通过“ $ {PYTHON_SRC_DIR} / Lib / ctypes / __ init __。py”(在第15附近):
    • OSX 9 x64
      • Python 2.7.10 x64
        >>> import ctypes
        >>> ctypes.sizeof(ctypes.c_void_p) * 8
        64
    • Ubuntu 16 x64
      • Python 3.5.2 x64
        >>> import ctypes
        >>> ctypes.sizeof(ctypes.c_void_p) * 8
        64
      • Python 3.6.4 x86
        >>> import ctypes
        >>> ctypes.sizeof(ctypes.c_void_p) * 8
        32
    • 赢10 x64
      • Python 3.5.4 x64
        >>> import ctypes
        >>> ctypes.sizeof(ctypes.c_void_p) * 8
        64
      • Python 3.6.2 x86
        >>> import ctypes
        >>> ctypes.sizeof(ctypes.c_void_p) * 8
        32


  1. [Python 3.Docs]:平台。架构可执行文件= sys.executable,位=”,链接=” !!! 在OSX上不可靠!由于采用多体系结构可执行文件(或.dylib)格式(在某些情况下,使用#2。):
    • OSX 9 x64
      • Python 2.7.10 x64
        >>> import platform
        >>> platform.architecture()
        ('64bit', '')
    • Ubuntu 16 x64
      • Python 3.5.2 x64
        >>> import platform
        >>> platform.architecture()
        ('64bit', 'ELF')
      • Python 3.6.4 x86
        >>> import platform
        >>> platform.architecture()
        ('32bit', 'ELF')
    • 赢10 x64
      • Python 3.5.4 x64
        >>> import platform
        >>> platform.architecture()
        ('64bit', 'WindowsPE')
      • Python 3.6.2 x86
        >>> import platform
        >>> platform.architecture()
        ('32bit', 'WindowsPE')


  1. me脚的解决方法(gainarie)- 通过[Python 3.Docs]:os调用外部命令([man7]:FILE(1)系统命令#4的局限性适用(有时可能甚至无法使用):
    • OSX 9 x64
      • Python 2.7.10 x64
        >>> import os
        >>> os.system("file {0:s}".format(os.path.realpath(sys.executable)))
        /opt/OPSWbuildtools/2.0.6/bin/python2.7.global: Mach-O 64-bit executable x86_64
    • Ubuntu 16 x64
      • Python 3.5.2 x64
        >>> import os
        >>> os.system("file {0:s}".format(os.path.realpath(sys.executable)))
        /usr/bin/python3.5: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=59a8ef36ca241df24686952480966d7bc0d7c6ea, stripped
      • Python 3.6.4 x86
        >>> import os
        >>> os.system("file {0:s}".format(os.path.realpath(sys.executable)))
        /home/cfati/Work/Dev/Python-3.6.4/python: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=5c3d4eeadbd13cd91445d08f90722767b0747de2, not stripped
    • 赢10 x64
      • 文件工具不存在,还有其他第三方工具可以使用,但我不会坚持使用它们


具体

  1. 通过[Python 3.Docs]检查环境变量(例如%PROCESSOR_ARCHITECTURE%(或其他)):操作系统。环境
    • 赢10 x64
      • Python 3.5.4 x64
        >>> import os
        >>> os.environ["PROCESSOR_ARCHITECTURE"]
        'AMD64'
      • Python 3.6.2 x86
        >>> import os
        >>> os.environ["PROCESSOR_ARCHITECTURE"]
        'x86'


  1. [Python 3.Docs]:sys。版本(也显示在1条第一线启动解释时)
    • 检查#1。

Grouping everything…

Considering that:

  • The question is asked for OSX (I have an old (and cracked) VM with an ancient Python version)
  • My main env is Win
  • I only have the 32bit version installed on Win (and I built a “crippled” one on Lnx)

I’m going to exemplify on all 3 platforms, using Python 3 and Python 2.

  1. Check [Python 3.Docs]: sys.maxsize value – compare it to 0x100000000 (2 ** 32): greater for 64bit, smaller for 32bit:
    • OSX 9 x64:
      • Python 2.7.10 x64:
        >>> import sys
        >>> "Python {0:s} on {1:s}".format(sys.version, sys.platform)
        'Python 2.7.10 (default, Oct 14 2015, 05:51:29) \n[GCC 4.8.2] on darwin'
        >>> hex(sys.maxsize), sys.maxsize > 0x100000000
        ('0x7fffffffffffffff', True)
        
    • Ubuntu 16 x64:
      • Python 3.5.2 x64:
        >>> import sys
        >>> "Python {0:s} on {1:s}".format(sys.version, sys.platform)
        'Python 3.5.2 (default, Nov 23 2017, 16:37:01) \n[GCC 5.4.0 20160609] on linux'
        >>> hex(sys.maxsize), sys.maxsize > 0x100000000
        ('0x7fffffffffffffff', True)
        
      • Python 3.6.4 x86:
        >>> import sys
        >>> "Python {0:s} on {1:s}".format(sys.version, sys.platform)
        'Python 3.6.4 (default, Apr 25 2018, 23:55:56) \n[GCC 5.4.0 20160609] on linux'
        >>> hex(sys.maxsize), sys.maxsize > 0x100000000
        ('0x7fffffff', False)
        
    • Win 10 x64:
      • Python 3.5.4 x64:
        >>> import sys
        >>> "Python {0:s} on {1:s}".format(sys.version, sys.platform)
        'Python 3.5.4 (v3.5.4:3f56838, Aug  8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] on win32'
        >>> hex(sys.maxsize), sys.maxsize > 0x100000000
        ('0x7fffffffffffffff', True)
        
      • Python 3.6.2 x86:
        >>> import sys
        >>> "Python {0:s} on {1:s}".format(sys.version, sys.platform)
        'Python 3.6.2 (v3.6.2:5fd33b5, Jul  8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32'
        >>> hex(sys.maxsize), sys.maxsize > 0x100000000
        ('0x7fffffff', False)
        


  1. Use [Python 3.Docs]: struct.calcsize(format) to determine the object size produced by the (pointer) format. In other words, determines the pointer size (sizeof(void*)):
    • OSX 9 x64:
      • Python 2.7.10 x64:
        >>> import struct
        >>> struct.calcsize("P") * 8
        64
        
    • Ubuntu 16 x64:
      • Python 3.5.2 x64:
        >>> import struct
        >>> struct.calcsize("P") * 8
        64
        
      • Python 3.6.4 x86:
        >>> import struct
        >>> struct.calcsize("P") * 8
        32
        
    • Win 10 x64:
      • Python 3.5.4 x64:
        >>> import struct
        >>> struct.calcsize("P") * 8
        64
        
      • Python 3.6.2 x86:
        >>> import struct
        >>> struct.calcsize("P") * 8
        32
        


  1. Use [Python 3.Docs]: ctypes – A foreign function library for Python. It also boils down to determining the size of a pointer (sizeof(void*)). As a note, ctypes uses #2. (not necessarily for this task) via “${PYTHON_SRC_DIR}/Lib/ctypes/__init__.py” (around line #15):
    • OSX 9 x64:
      • Python 2.7.10 x64:
        >>> import ctypes
        >>> ctypes.sizeof(ctypes.c_void_p) * 8
        64
        
    • Ubuntu 16 x64:
      • Python 3.5.2 x64:
        >>> import ctypes
        >>> ctypes.sizeof(ctypes.c_void_p) * 8
        64
        
      • Python 3.6.4 x86:
        >>> import ctypes
        >>> ctypes.sizeof(ctypes.c_void_p) * 8
        32
        
    • Win 10 x64:
      • Python 3.5.4 x64:
        >>> import ctypes
        >>> ctypes.sizeof(ctypes.c_void_p) * 8
        64
        
      • Python 3.6.2 x86:
        >>> import ctypes
        >>> ctypes.sizeof(ctypes.c_void_p) * 8
        32
        


  1. [Python 3.Docs]: platform.architecture(executable=sys.executable, bits=”, linkage=”) !!! NOT reliable on OSX !!! due to multi arch executable (or .dylib) format (in some cases, uses #2.):
    • OSX 9 x64:
      • Python 2.7.10 x64:
        >>> import platform
        >>> platform.architecture()
        ('64bit', '')
        
    • Ubuntu 16 x64:
      • Python 3.5.2 x64:
        >>> import platform
        >>> platform.architecture()
        ('64bit', 'ELF')
        
      • Python 3.6.4 x86:
        >>> import platform
        >>> platform.architecture()
        ('32bit', 'ELF')
        
    • Win 10 x64:
      • Python 3.5.4 x64:
        >>> import platform
        >>> platform.architecture()
        ('64bit', 'WindowsPE')
        
      • Python 3.6.2 x86:
        >>> import platform
        >>> platform.architecture()
        ('32bit', 'WindowsPE')
        


  1. Lame workaround (gainarie) – invoke an external command ([man7]: FILE(1)) via [Python 3.Docs]: os.system(command). The limitations of #4. apply (sometimes it might not even work):
    • OSX 9 x64:
      • Python 2.7.10 x64:
        >>> import os
        >>> os.system("file {0:s}".format(os.path.realpath(sys.executable)))
        /opt/OPSWbuildtools/2.0.6/bin/python2.7.global: Mach-O 64-bit executable x86_64
        
    • Ubuntu 16 x64:
      • Python 3.5.2 x64:
        >>> import os
        >>> os.system("file {0:s}".format(os.path.realpath(sys.executable)))
        /usr/bin/python3.5: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=59a8ef36ca241df24686952480966d7bc0d7c6ea, stripped
        
      • Python 3.6.4 x86:
        >>> import os
        >>> os.system("file {0:s}".format(os.path.realpath(sys.executable)))
        /home/cfati/Work/Dev/Python-3.6.4/python: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=5c3d4eeadbd13cd91445d08f90722767b0747de2, not stripped
        
    • Win 10 x64:
      • file utility is not present, there are other 3rd Party tools that can be used, but I’m not going to insist on them


Win specific:

  1. Check env vars (e.g. %PROCESSOR_ARCHITECTURE% (or others)) via [Python 3.Docs]: os.environ:
    • Win 10 x64:
      • Python 3.5.4 x64:
        >>> import os
        >>> os.environ["PROCESSOR_ARCHITECTURE"]
        'AMD64'
        
      • Python 3.6.2 x86:
        >>> import os
        >>> os.environ["PROCESSOR_ARCHITECTURE"]
        'x86'
        


  1. [Python 3.Docs]: sys.version (also displayed in the 1st line when starting the interpreter)
    • Check #1.

回答 9

struct.calcsize("P")返回存储单个指针所需的字节大小。在32位系统上,它将返回4个字节。在64位系统上,它将返回8个字节。

因此,32如果您运行的是32位python并且64运行的是64 位python,则会返回以下内容:

Python 2

import struct;print struct.calcsize("P") * 8

Python 3

import struct;print(struct.calcsize("P") * 8)

struct.calcsize("P") returns size of the bytes required to store a single pointer. On a 32-bit system, it would return 4 bytes. On a 64-bit system, it would return 8 bytes.

So the following would return 32 if you’re running 32-bit python and 64 if you’re running 64-bit python:

Python 2

import struct;print struct.calcsize("P") * 8

Python 3

import struct;print(struct.calcsize("P") * 8)

回答 10

python -VV在命令行中执行a 。它应该返回版本。

Do a python -VV in the command line. It should return the version.


回答 11

C:\Users\xyz>python

Python 2.7.6 (default, Nov XY ..., 19:24:24) **[MSC v.1500 64 bit (AMD64)] on win
32**
Type "help", "copyright", "credits" or "license" for more information.
>>>

在cmd中点击python后

C:\Users\xyz>python

Python 2.7.6 (default, Nov XY ..., 19:24:24) **[MSC v.1500 64 bit (AMD64)] on win
32**
Type "help", "copyright", "credits" or "license" for more information.
>>>

after hitting python in cmd


回答 12

import sys
print(sys.version)

3.5.1(v3.5.1:37a07cee5969,2015年12月6日,01:54:25)[MSC v.1900 64位(AMD64) ]

import sys
print(sys.version)

3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)]


回答 13

根据abe32的回答,

import sys
n_bits = 32 << bool(sys.maxsize >> 32)

n_bits将具有32或64位。

Based On abe32’s answer,

import sys
n_bits = 32 << bool(sys.maxsize >> 32)

n_bits will have 32 or 64 bits.


回答 14

对于32位,它将返回32,对于64位,它将返回64

import struct
print(struct.calcsize("P") * 8)

For 32 bit it will return 32 and for 64 bit it will return 64

import struct
print(struct.calcsize("P") * 8)

回答 15

平台架构不是可靠的方法。相反,我们:

$ arch -i386 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 2147483647)
>>> ^D
$ arch -x86_64 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 9223372036854775807)

Platform Architecture is not the reliable way. Instead us:

$ arch -i386 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 2147483647)
>>> ^D
$ arch -x86_64 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 9223372036854775807)

回答 16

platform.architecture() 是有问题的(而且昂贵)。

sys.maxsize > 2**32从Py2.6开始方便地进行测试。

这是对实际(默认)指针大小的可靠测试,至少从Py2.3:开始兼容struct.calcsize('P') == 8。也:ctypes.sizeof(ctypes.c_void_p) == 8

注意:可以使用gcc选项构建-mx32,这是64位体系结构的应用程序,但是默认使用32位指针(节省内存和速度)。’sys.maxsize = ssize_t’可能不严格表示C指针大小(2**31 - 1无论如何通常如此)。而且,有些系统的代码和数据的指针大小不同,因此需要澄清辨别“ 32位或64位模式”的目的是什么?

platform.architecture() is problematic (and expensive).

Conveniently test for sys.maxsize > 2**32 since Py2.6 .

This is a reliable test for the actual (default) pointer size and compatible at least since Py2.3: struct.calcsize('P') == 8. Also: ctypes.sizeof(ctypes.c_void_p) == 8.

Notes: There can be builds with gcc option -mx32 or so, which are 64bit architecture applications, but use 32bit pointers as default (saving memory and speed). ‘sys.maxsize = ssize_t’ may not strictly represent the C pointer size (its usually 2**31 - 1 anyway). And there were/are systems which have different pointer sizes for code and data and it needs to be clarified what exactly is the purpose of discerning “32bit or 64bit mode?”