标签归档:python-3.x

如何在python 3中将二进制数据写入stdout?

问题:如何在python 3中将二进制数据写入stdout?

在python 2.x中,我可以这样做:

import sys, array
a = array.array('B', range(100))
a.tofile(sys.stdout)

但是现在,我得到了TypeError: can't write bytes to text stream。我应该使用一些秘密编码吗?

In python 2.x I could do this:

import sys, array
a = array.array('B', range(100))
a.tofile(sys.stdout)

Now however, I get a TypeError: can't write bytes to text stream. Is there some secret encoding that I should use?


回答 0

更好的方法:

import sys
sys.stdout.buffer.write(b"some binary data")

A better way:

import sys
sys.stdout.buffer.write(b"some binary data")

回答 1

import os
os.write(1, a.tostring())

或者,os.write(sys.stdout.fileno(), …)如果这比1您可读性强。

import os
os.write(1, a.tostring())

or, os.write(sys.stdout.fileno(), …) if that’s more readable than 1 for you.


回答 2

只能在Python 3中使用的惯用方式是:

with os.fdopen(sys.stdout.fileno(), "wb", closefd=False) as stdout:
    stdout.write(b"my bytes object")
    stdout.flush()

好地方是它使用普通的文件对象接口,每个人都在Python中使用它。

请注意,我正在设置closefd=False为避免sys.stdout退出with块时关闭。否则,您的程序将无法再打印到标准输出。但是,对于其他类型的文件描述符,您可能要跳过该部分。

An idiomatic way of doing so, which is only available for Python 3, is:

with os.fdopen(sys.stdout.fileno(), "wb", closefd=False) as stdout:
    stdout.write(b"my bytes object")
    stdout.flush()

The good part is that it uses the normal file object interface, which everybody is used to in Python.

Notice that I’m setting closefd=False to avoid closing sys.stdout when exiting the with block. Otherwise, your program wouldn’t be able to print to stdout anymore. However, for other kind of file descriptors, you may want to skip that part.


回答 3

如果您想在python3中指定编码,则仍然可以使用bytes命令,如下所示:

import os
os.write(1,bytes('Your string to Stdout','UTF-8'))

其中1是stdout的对应常规编号-> sys.stdout.fileno()

否则,如果您不关心编码,请使用:

import sys
sys.stdout.write("Your string to Stdout\n")

如果要使用不带编码的os.write,请尝试使用以下内容:

import os
os.write(1,b"Your string to Stdout\n")

In case you would like to specify an encoding in python3 you can still use the bytes command like below:

import os
os.write(1,bytes('Your string to Stdout','UTF-8'))

where 1 is the corresponding usual number for stdout –> sys.stdout.fileno()

Otherwise if you don’t care of the encoding just use:

import sys
sys.stdout.write("Your string to Stdout\n")

If you want to use the os.write without the encoding, then try to use the below:

import os
os.write(1,b"Your string to Stdout\n")

Windows在subprocess.call()上找不到文件

问题:Windows在subprocess.call()上找不到文件

我收到以下错误:

WindowsError: [Error 2] The system cannot find the file specified

我的代码是:

subprocess.call(["<<executable file found in PATH>>"])

Windows 7,64位。Python 3.x最新,稳定。

有任何想法吗?

谢谢,

I am getting the following error:

WindowsError: [Error 2] The system cannot find the file specified

My code is:

subprocess.call(["<<executable file found in PATH>>"])

Windows 7, 64 bit. Python 3.x latest, stable.

Any ideas?

Thanks,


回答 0

当命令是内置的shell时,请在调用中添加“ shell = True”。

例如,dir您将输入:

import subprocess
subprocess.call('dir', shell=True)

引用文档:

在Windows上唯一需要指定shell = True的时间是将要执行的命令内置到shell中(例如dir或copy)。您不需要shell = True即可运行批处理文件或基于控制台的可执行文件。

When the command is a shell built-in, add a ‘shell=True’ to the call.

E.g. for dir you would type:

import subprocess
subprocess.call('dir', shell=True)

To quote from the documentation:

The only time you need to specify shell=True on Windows is when the command you wish to execute is built into the shell (e.g. dir or copy). You do not need shell=True to run a batch file or console-based executable.


回答 1

在Windows上,我相信除非您通过subprocessPATH否则shell=True模块不会进入,因为它CreateProcess()在后台使用。但是,shell=True如果传递的参数可能来自程序外部,则可能存在安全风险。为了subprocess仍然能找到正确的可执行文件,你可以使用shutil.which。假设您中的可执行文件PATH名为frob

subprocess.call([shutil.which('frob'), arg1, arg2])

(这适用于Python 3.3及更高版本。)

On Windows, I believe the subprocess module doesn’t look in the PATH unless you pass shell=True because it use CreateProcess() behind the scenes. However, shell=True can be a security risk if you’re passing arguments that may come from outside your program. To make subprocess nonetheless able to find the correct executable, you can use shutil.which. Suppose the executable in your PATH is named frob:

subprocess.call([shutil.which('frob'), arg1, arg2])

(This works on Python 3.3 and above.)


回答 2

在Windows上,您必须通过cmd.exe进行调用。如Apalala所述,Windows命令不是作为单独的可执行文件在cmd.exe中实现的。

例如

subprocess.call(['cmd', '/c', 'dir'])

/ c告诉cmd运行以下命令

这比使用shell = True(允许shell注入)更安全。

On Windows you have to call through cmd.exe. As Apalala mentioned, Windows commands are implemented in cmd.exe not as separate executables.

e.g.

subprocess.call(['cmd', '/c', 'dir'])

/c tells cmd to run the follow command

This is safer than using shell=True, which allows shell injections.


回答 3

如果您使用的是Powershell,则将在其中subprocess.call(['powershell','-command','dir'])。Powershell支持大部分POSIX命令

If you are using powershell, then in it will be subprocess.call(['powershell','-command','dir']). Powershell supports a large portion of POSIX commands


回答 4

经过大量的抓挠之后,我发现在64位计算机上运行32位版本的python时,运行位于C:\ Windows \ System32 \中的文件是一个潜在的问题,这是由于Windows试图使该过程变得更智能,以及将对C:\ Windows \ System32的调用重定向到C:\ Windows \ SysWOW64。

我在这里找到了如何解决此问题的示例:http : //code.activestate.com/recipes/578035-disable-file-system-redirector/

After much head scratching, I discovered that running a file that is located in C:\Windows\System32\ while running a 32bit version of python on a 64bit machine is a potential issue, due to Windows trying to out-smart the process, and redirect calls to C:\Windows\System32 to C:\Windows\SysWOW64.

I found an example of how to fix this here: http://code.activestate.com/recipes/578035-disable-file-system-redirector/


回答 5

引用文档:

“在Python 3.5之前,这三个函数包含用于子过程的高级API。您现在可以在许多情况下使用run(),但是许多现有代码都调用了这些函数。”

因此:对于Python 3.5及更高版本,请使用subprocess.run而不是subprocess.call

To quote from the documentation:

“Prior to Python 3.5, these three functions comprised the high level API to subprocess. You can now use run() in many cases, but lots of existing code calls these functions.”

SO: instead of subprocess.call use subprocess.run for Python 3.5 and above


回答 6

在调用PHP时遇到了相同的问题。原因是PHP不在PATH中,所以找不到命令PHP。但是PowerShell发现它确实存在于当前位置,如果我信任此命令,建议将“ PHP”替换为“。\ PHP”。然后运行良好。

I met the same issue while I was calling a PHP. The reason is PHP isn’t in PATH so the command PHP was not found. But PowerShell found it does exist in the current location and it suggests replacing the ‘PHP’ by the ‘.\PHP’ if I trust this command. Then it runs well.


用户定义类的类型提示

问题:用户定义类的类型提示

似乎找不到确切的答案。我想为一个函数提供类型提示,该类型是我定义的一些自定义类,称为它CustomClass()

然后让我们说在某个函数中调用它FuncA(arg),我有一个名为的参数arg。键入提示的正确方法FuncA是:

def FuncA(arg: CustomClass):

或者是:

def FuncA(Arg:Type[CustomClass]):

Couldn’t seem to find a definitive answer. I want to do a type hint for a function and the type being some custom class that I have defined, called it CustomClass().

And then let’s say in some function, call it FuncA(arg), I have one argument named arg. Would the correct way to type hint FuncA be:

def FuncA(arg: CustomClass):

Or would it be:

def FuncA(Arg:Type[CustomClass]):?


回答 0

前者是正确的,如果arg接受一个实例CustomClass

def FuncA(arg: CustomClass):
    #     ^ instance of CustomClass

如果您想要CustomClass本身(或子类型),则应编写:

from typing import Type  # you have to import Type

def FuncA(arg: Type[CustomClass]):
    #     ^ CustomClass (class object) itself

就像在有关打字的文档中写的那样:

class typing.Type(Generic[CT_co])

带注释的变量C可以接受type的值C。相反,带注释Type[C]的变量可以接受本身是类的值 -具体地说,它将接受的类对象C

该文档包含有关int该类的示例:

a = 3         # Has type 'int'
b = int       # Has type 'Type[int]'
c = type(a)   # Also has type 'Type[int]'

The former is correct, if arg accepts an instance of CustomClass:

def FuncA(arg: CustomClass):
    #     ^ instance of CustomClass

In case you want the class CustomClass itself (or a subtype), then you should write:

from typing import Type  # you have to import Type

def FuncA(arg: Type[CustomClass]):
    #     ^ CustomClass (class object) itself

Like it is written in the documentation about Typing:

class typing.Type(Generic[CT_co])

A variable annotated with C may accept a value of type C. In contrast, a variable annotated with Type[C] may accept values that are classes themselves – specifically, it will accept the class object of C.

The documentation includes an example with the int class:

a = 3         # Has type 'int'
b = int       # Has type 'Type[int]'
c = type(a)   # Also has type 'Type[int]'

如何使IPython Notebook运行Python 3?

问题:如何使IPython Notebook运行Python 3?

我是Python的新手。

  1. 我安装了Anaconda,效果很好。
  2. 我按照Anaconda cmd行说明设置了Python 3环境,效果很好。
  3. 我将Anaconda的Python 3环境设置为Pycharm的解释器,效果很好。
  4. 我启动了Anaconda“ launcher.app”,并启动了IPython Notebook。但是,iPython Notebook正在运行Python 2而不是3。

经过三个多小时的Google搜索,我无法弄清楚如何将IPython Notebook设置为运行Python 3而不是2。

I am new to Python to bear with me.

  1. I installed Anaconda, works great.
  2. I setup a Python 3 environment following the Anaconda cmd line instructions, works great.
  3. I setup Anaconda’s Python 3 environment as Pycharm’s interpreter, works great.
  4. I launched the Anaconda “launcher.app” and launched IPython Notebook. However, iPython Notebook is running Python 2 not 3.

Over three hours of Googling later, I cannot figure out how to set IPython Notebook to run Python 3 instead of 2.


回答 0

要将IPython Notebook设置为在MAC 10.9上运行Python 3而不是2,我执行了以下步骤

$ sudo pip3 install ipython[all]

然后

$ ipython3 notebook

To set IPython Notebook to run Python 3 instead of 2 on my MAC 10.9, I did the following steps

$ sudo pip3 install ipython[all]

Then

$ ipython3 notebook


回答 1

对于Linux 16.04 Ubuntu,您可以使用

sudo apt-get install ipython3

然后使用

ipython3 notebook

在浏览器中打开笔记本。如果您有任何笔记本用python 2保存,则打开笔记本后它将自动将其转换为Python 3。

For linux 16.04 Ubuntu you can use

sudo apt-get install ipython3

and then use

ipython3 notebook

to open the notebook in the browser. If you have any notebooks saved with python 2 then it will automatically convert them to Python 3 once you open the notebook.


回答 2

要在带有Anaconda的Windows 10上将jupyter与python 3而不是python 2一起使用,我在anaconda提示符下执行了以下步骤:

pip3 install ipython[all]

然后,

ipython3 notebook

To use jupyter with python 3 instead of python 2 on my Windows 10 with Anaconda, I did the following steps on anaconda prompt:

pip3 install ipython[all]

Then,

ipython3 notebook

回答 3

您的发行版中有包装吗?如果您使用的是ubuntu,则必须安装ipython3-notebook软件包。如果没有,也许您必须使用python3安装ipython。

如果您已经运行(因为默认情况下是python2)

python setup.py

您必须改为跑步

python3 setup.py install

使用python3而不是python2安装软件包。这将是ipython3的新安装。

Is there a package from your distro? If you’re using ubuntu you must to install the ipython3-notebook package. If not, maybe you must to install ipython with python3.

If you’ve run (because it’s python2 by default)

python setup.py

you must to run instead

python3 setup.py install

to install a package with python3 instead python2. This will be a new instalation of ipython3.


回答 4

在Anaconda的“ launcher.app”中,有“环境:”下拉菜单。默认环境称为“根”。为了使用其他环境启动应用程序,只需从列表中选择所需的环境以使其处于活动状态即可。

In Anaconda “launcher.app” there is “Environment:” pull down menu. The default environment is called “root”. In order to launch application using another environment, just select the desired environment from the list, to make it active.


回答 5

如果您正在运行anaconda,则安装笔记本/ jupyter的首选方法是使用conda:

conda install jupyter

If you are running anaconda, then the preferred way to install notebook/jupyter is using conda:

conda install jupyter

回答 6

如果在jupyter笔记本电脑上都有这两个版本,则可以从菜单中更改内核。

If you have both version available on jupyter notebook, you can change the kernel from menu.


回答 7

适当切换此答案中2和3的角色。

假设您已经安装了带有python 2内核的jupyter设置和带有python 3的anaconda环境。激活python 3环境,然后运行

conda install ipykernel

之后,您可以在创建新笔记本或从内核菜单中选择正在运行的笔记本中同时选择2和3内核。

Switch the role of 2 and 3 in this answer as appropriate.

Say you already have jupyter setup with a python 2 kernel and an anaconda environment with python 3. Activate the python 3 enviroment and then run

conda install ipykernel

After that you can select both a 2 and 3 kernel when creating a new notebook, or in a running notebook from the kernels menu.


回答 8

另一个解决方案是使用python3 创建virtualenv

在此环境中,在此处安装tensorflow(您喜欢的版本):

pip install tensorflow

从那里运行您的jupyter!

Another solution would be to create a virtualenv with python3:

From this environment, install tensorflow (the version you prefer) there:

pip install tensorflow

Run your jupyter from there !


Windows 10无法识别Conda命令

问题:Windows 10无法识别Conda命令

我按照以下说明在Windows 10上安装了Anaconda 4.4.0(Python 3.6版本):https : //www.continuum.io/downloads。但是,当我打开命令提示符窗口并尝试编写时

conda list

我得到了

无法识别’conda’命令…

错误。

我试着跑

set PATH=%PATH%;C:\Users\Alex\Anaconda3

但这没有帮助。我还读到我可能需要编辑.bashrc文件,但是我不知道如何访问该文件以及如何编辑它。

I installed Anaconda 4.4.0 (Python 3.6 version) on Windows 10 by following the instructions here: https://www.continuum.io/downloads. However, when I open the Command prompt window and try to write

conda list

I get the

‘conda’ command is not recognized…

error.

I tried to run

set PATH=%PATH%;C:\Users\Alex\Anaconda3

but it didn’t help. I also read that I might need to edit my .bashrc file, but I don’t know how to access this file, and how I should edit it.


回答 0

在Windows中,您必须将路径设置为将Anaconda3安装到的位置。

对我来说,我将anaconda3安装到中C:\Anaconda3。因此,您需要在路径变量中添加C:\Anaconda3C:\Anaconda3\Scripts\,例如set PATH=%PATH%;C:\Anaconda3;C:\Anaconda3\Scripts\

您可以通过powershell进行此操作(请参见上文,https: //msdn.microsoft.com/zh-cn/library/windows/desktop/bb776899(v = vs.85).aspx ),或按一下windows键→输入environment→选择从settings→→ edit environment variables for your account选择Path变量Edit→→ New

要测试它,请打开一个新的dos外壳,您现在应该可以使用conda命令。例如,尝试conda --version

In Windows, you will have to set the path to the location where you installed Anaconda3 to.

For me, I installed anaconda3 into C:\Anaconda3. Therefore you need to add C:\Anaconda3 as well as C:\Anaconda3\Scripts\ to your path variable, e.g. set PATH=%PATH%;C:\Anaconda3;C:\Anaconda3\Scripts\.

You can do this via powershell (see above, https://msdn.microsoft.com/en-us/library/windows/desktop/bb776899(v=vs.85).aspx ), or hit the windows key → enter environment → choose from settingsedit environment variables for your account → select Path variable → EditNew.

To test it, open a new dos shell, and you should be able to use conda commands now. E.g., try conda --version.


回答 1

在conda 4.6之后,情况发生了变化

程序“ Anaconda Prompt”和“ Anaconda Powershell”会conda自动为您显示命令。在启动菜单中找到它们。

如果您不想使用上面的提示,请尝试conda使用普通cmd.exe和Powershell。阅读以下内容。


暴露conda在每个shell

以下内容的目的是使命令在Windows condacmd.exe和Powershell中均可用。

如果在Anaconda安装过程中已选中“将Anaconda添加到我的PATH环境变量”,请跳过步骤1。

  1. 如果Anaconda仅安装用于当前用途,则将%USERPROFILE%\Anaconda3\condabin(我的意思是condabin,不是Scripts)添加到环境变量PATH(用户一个)中。如果您的计算机上的所有用户都安装了Anaconda,请添加C:\ProgramData\Anaconda3\condabin到中PATH

    如何在Windows上设置系统环境变量?

  2. 打开一个新的 Powershell,一次运行以下命令进行初始化conda

    conda init

这些步骤确保conda命令显示在您的cmd.exePowershell中。


扩展阅读:conda init来自Conda 4.6

警告:将新内容添加到您的中,\path\to\anaconda3\condabin但不要添加。这是4.6中引入的重大更改\path\to\anaconda3\ScriptsPATHconda

激活脚本初始化fron conda4.6发布日志

Conda 4.6添加了广泛的初始化支持,因此可以使用新conda activate命令的外壳比以前更多。有关更多信息,请阅读的输出。conda init –help对于这种新的工作方式,我们特别感到兴奋,因为消除了修改需求,PATH使Conda对系统上其他软件的破坏性大大降低。

在过去,这\path\to\anaconda3\Scripts是您的必备条件PATH。它conda同时在“基本”环境中公开命令和默认Python。

conda4.6 之后,conda相关命令分为condabin。这样就可以公开仅命令,conda而无需从“基本”环境中激活Python。

参考文献

Things have been changed after conda 4.6.

Programs “Anaconda Prompt” and “Anaconda Powershell” expose the command conda for you automatically. Find them in your startup menu.

If you don’t wanna use the prompts above and try to make conda available in a normal cmd.exe and a Powershell. Read the following content.


Expose conda in Every Shell

The purpose of the following content is to make command conda available both in cmd.exe and Powershell on Windows.

If you have already checked “Add Anaconda to my PATH environment variable” during Anaconda installation, skip step 1.

  1. If Anaconda is installed for the current use only, add %USERPROFILE%\Anaconda3\condabin (I mean condabin, not Scripts) into the environment variable PATH (the user one). If Anaconda is installed for all users on your machine, add C:\ProgramData\Anaconda3\condabin into PATH.

    How do I set system environment variables on Windows?

  2. Open a new Powershell, run the following command once to initialize conda.

    conda init
    

These steps make sure the conda command is exposed into your cmd.exe and Powershell.


Extended Reading: conda init from Conda 4.6

Caveat: Add the new \path\to\anaconda3\condabin but not \path\to\anaconda3\Scripts into your PATH. This is a big change introduced in conda 4.6.

Activation script initialization fron conda 4.6 release log

Conda 4.6 adds extensive initialization support so that more shells than ever before can use the new conda activate command. For more information, read the output from conda init –help We’re especially excited about this new way of working, because removing the need to modify PATH makes Conda much less disruptive to other software on your system.

In the old days, \path\to\anaconda3\Scripts is the one to be put into your PATH. It exposes command conda and the default Python from “base” environment at the same time.

After conda 4.6, conda related commands are separated into condabin. This makes it possible to expose ONLY command conda without activating the Python from “base” environment.

References


回答 2

现在在Windows上安装anaconda时,它不会自动添加Python或Conda。

如果您不知道conda和/或python在哪里,请在anaconda提示符下键入以下命令

接下来,您可以在命令提示符下使用setx命令将Python和Conda添加到路径中。

接下来,关闭该命令提示符并打开一个新命令。恭喜您现在可以使用conda和python

来源:https : //medium.com/@GalarnykMichael/install-python-on-windows-anaconda-c63c7c3d1444

When you install anaconda on windows now, it doesn’t automatically add Python or Conda.

If you don’t know where your conda and/or python is, you type the following commands into your anaconda prompt

Next, you can add Python and Conda to your path by using the setx command in your command prompt.

Next close that command prompt and open a new one. Congrats you can now use conda and python

Source: https://medium.com/@GalarnykMichael/install-python-on-windows-anaconda-c63c7c3d1444


回答 3

用于Windows的最新版本的Anaconda安装程序还将为“ Anaconda Prompt”和“ Anaconda Powershell Prompt”安装Windows启动器。如果您使用其中之一而不是常规的Windows cmd Shell,则conda默认情况下,此Shell中应使用命令python等。

The newest version of the Anaconda installer for Windows will also install a windows launcher for “Anaconda Prompt” and “Anaconda Powershell Prompt”. If you use one of those instead of the regular windows cmd shell, the conda command, python etc. should be available by default in this shell.


回答 4

如果要在Windows的常规cmd中使用Anaconda,则需要向Path env变量添加几个路径。

这些路径是(根据 PC 上的Anaconda版本文件夹可能是Anaconda2而不是Anaconda2):

\Users\YOUR_USER\Anaconda3
\Users\YOUR_USER\Anaconda3\Library\mingw-w64\bin
\Users\YOUR_USER\Anaconda3\Library\usr\bin
\Users\YOUR_USER\Anaconda3\Library\bin
\Users\YOUR_USER\Anaconda3\Scripts
\Users\YOUR_USER\Anaconda3\bin

If you want to use Anaconda in regular cmd on windows you need to add several paths to your Path env variable.

Those paths are (instead of Anaconda3 the folder may be Anaconda2 depending on the Anaconda version on your PC):

\Users\YOUR_USER\Anaconda3
\Users\YOUR_USER\Anaconda3\Library\mingw-w64\bin
\Users\YOUR_USER\Anaconda3\Library\usr\bin
\Users\YOUR_USER\Anaconda3\Library\bin
\Users\YOUR_USER\Anaconda3\Scripts
\Users\YOUR_USER\Anaconda3\bin

回答 5

一个小时前,我也遇到了同样的问题。我试图用Python安装QuTip Quantum Toolbox 不幸的是,我没有及时发现该页面。假设您已经下载了Anaconda安装程序并运行到最后。天真地,我在Windows 10中打开了命令提示符,然后继续输入qutip installation docs中给出的以下命令。

康达创建-n qutip-env

conda配置-添加通道conda-forge

康达安装qutip

但是,当我键入第一行时,我得到以下响应

不能将conda识别为内部或外部命令,可操作程序或批处理文件

错误消息

我继续尝试了一些其他操作,如该数字 错误消息所示。 最后,在访问了多个conda网站之后,我了解了如何解决此问题。在底部的搜索栏中输入Anaconda提示符,如下所示(在同一位置您赞美Cortana) Anaconda提示符

一旦您在这里,所有的conda命令将照常工作

I had also faced the same problem just an hour back. I was trying to install QuTip Quantum Toolbox in Python Unfortunately, I didn’t stumble onto this page in time. Say you have downloaded Anaconda installer and run it until the end. Naively, I opened the command prompt in windows 10 and proceded to type the following commands as given in the qutip installation docs.

conda create -n qutip-env

conda config –append channels conda-forge

conda install qutip

But as soon as I typed the first line I got the following response

conda is not recognized as an internal or external command, operable program or batch file

error messsage

I went ahead and tried some other things as seen in this figures error message Finally after going through a number conda websites, I understood how one fixes this problem. Type Anaconda prompt in the search bar at the bottom like this (same place where you hail Cortana) Anaconda prompt

Once you are here all the conda commands will work as usual


回答 6

如果您已安装Visual Studio 2017(专业版)

安装位置:

C:\ProgramData\Anaconda3\Scripts

如果您不希望将其放入Windows的path环境变量中并重新启动,可以通过以下简单方式运行它:

C:\>"C:\ProgramData\Anaconda3\Scripts\conda.exe" update qt pyqt

If you have installed Visual studio 2017 (profressional)

The install location:

C:\ProgramData\Anaconda3\Scripts

If you do not want the hassle of putting this in your path environment variable on windows and restarting you can run it by simply:

C:\>"C:\ProgramData\Anaconda3\Scripts\conda.exe" update qt pyqt

回答 7

甚至在我初次安装Anaconda时遇到了同样的问题。它说找不到“ conda”命令。

因此,我只设置了两个值[在PATH变量中添加了Anaconda的两个新路径]系统环境变量:C:\ Users \ mshas \ Anaconda2 \和C:\ Users \ mshas \ Anaconda2 \ Scripts

很多人忘记添加第二个变量“ Scripts”,而只需添加“ conda”命令即可。

Even I got the same problem when I’ve first installed Anaconda. It said ‘conda’ command not found.

So I’ve just setup two values[added two new paths of Anaconda] system environment variables in the PATH variable which are: C:\Users\mshas\Anaconda2\ & C:\Users\mshas\Anaconda2\Scripts

Lot of people forgot to add the second variable which is “Scripts” just add that then ‘conda’ command works.


回答 8

您需要将C://…/Anaconda3安装文件中的python.exe以及C://…/Anaconda3/Scripts添加到PATH。

首先转到您的安装目录,在我的情况下,它安装在C:// Users / user / Anaconda3中,并按住Shift键并单击鼠标右键,然后按“在此处打开命令窗口”,或者如果是powershell,则可能是“在此处打开powershell” ,只需编写cmd并按Enter键即可运行命令窗口。然后运行以下命令setx PATH%cd%

然后转到C:// Users / user / Anaconda3 / Scripts并在上面打开命令窗口,然后运行相同的命令“ setx PATH%cd%”

You need to add the python.exe in C://…/Anaconda3 installation file as well as C://…/Anaconda3/Scripts to PATH.

First go to your installation directory, in my case it is installed in C://Users/user/Anaconda3 and shift+right click and press “Open command window here” or it might be “Open powershell here”, if it is powershell, just write cmd and hit enter to run command window. Then run the following command setx PATH %cd%

Then go to C://Users/user/Anaconda3/Scripts and open the command window there as above, then run the same command “setx PATH %cd%”


回答 9

情况#1 您应设置3条路径:

%ANACONDAPATH%;
%ANACONDAPATH%\Scripts;
%ANACONDAPATH%\Library\bin;

它将解决问题:

C:\WINDOWS\system32>conda update conda
Solving environment: failed

CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://repo.anaconda.com/pkgs/msys2/noarch/repodata.json.bz2>
Elapsed: -
...

案例2 您还可以使用Anaconda Promd(用于Win10)代替CLI(cmd.exe)

case #1 You should set 3 path:

%ANACONDAPATH%;
%ANACONDAPATH%\Scripts;
%ANACONDAPATH%\Library\bin;

It will solve problem:

C:\WINDOWS\system32>conda update conda
Solving environment: failed

CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://repo.anaconda.com/pkgs/msys2/noarch/repodata.json.bz2>
Elapsed: -
...

case #2 Also you can use Anaconda Promd (for Win10) instead CLI (cmd.exe)


回答 10

为了防止SSL出现其他问题,您应该将所有这些都添加到Path中:

 SETX PATH "%PATH%;C:\<path>\Anaconda3;C:\<path>\Anaconda3\Scripts;C:\<path>\Anaconda3\Library\bin"

请求(由SSLError引起(“由于SSL模块不可用,无法连接到HTTPS URL。”)PyCharm请求网站中的错误

To prevent having further issues with SSL you should add all those to Path :

 SETX PATH "%PATH%;C:\<path>\Anaconda3;C:\<path>\Anaconda3\Scripts;C:\<path>\Anaconda3\Library\bin"

Requests (Caused by SSLError(“Can’t connect to HTTPS URL because the SSL module is not available.”) Error in PyCharm requesting website


在Jupyter Python Notebook中显示所有数据框列

问题:在Jupyter Python Notebook中显示所有数据框列

我想在Jupyter Notebook的数据框中显示所有列。Jupyter显示一些列,并在最后一列中添加点,如下图所示:

如何显示所有列?

I want to show all columns in a dataframe in a Jupyter Notebook. Jupyter shows some of the columns and adds dots to the last columns like in the following picture:

How can I display all columns?


回答 0

尝试如下显示max_columns设置:

import pandas as pd
from IPython.display import display

df = pd.read_csv("some_data.csv")
pd.options.display.max_columns = None
display(df)

要么

pd.set_option('display.max_columns', None)

编辑:熊猫0.11.0向后

不建议使用此功能,但在低于0.11.0的Pandas版本中,该max_columns设置指定如下:

pd.set_printoptions(max_columns=500)

Try the display max_columns setting as follows:

import pandas as pd
from IPython.display import display

df = pd.read_csv("some_data.csv")
pd.options.display.max_columns = None
display(df)

Or

pd.set_option('display.max_columns', None)

Edit: Pandas 0.11.0 backwards

This is deprecated but in versions of Pandas older than 0.11.0 the max_columns setting is specified as follows:

pd.set_printoptions(max_columns=500)

回答 1

我知道这个问题有点老了,但是以下内容在运行pandas 0.22.0和Python 3的Jupyter Notebook中为我工作:

import pandas as pd
pd.set_option('display.max_columns', <number of columns>)

您也可以对行执行相同的操作:

pd.set_option('display.max_rows', <number of rows>)

这样可以节省导入IPython的时间,并且pandas.set_option文档中还有更多选项:https ://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.set_option.html

I know this question is a little old but the following worked for me in a Jupyter Notebook running pandas 0.22.0 and Python 3:

import pandas as pd
pd.set_option('display.max_columns', <number of columns>)

You can do the same for the rows too:

pd.set_option('display.max_rows', <number of rows>)

This saves importing IPython, and there are more options in the pandas.set_option documentation: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.set_option.html


回答 2

适用于大型(但不是太大)DataFrame的Python 3.x

也许是因为我有较旧版本的熊猫,但在Jupyter笔记本上,这对我有用

import pandas as pd
from IPython.core.display import HTML

df=pd.read_pickle('Data1')
display(HTML(df.to_html()))

Python 3.x for large (but not too large) DataFrames

Maybe because I have an older version of pandas but on Jupyter notebook this work for me

import pandas as pd
from IPython.core.display import HTML

df=pd.read_pickle('Data1')
display(HTML(df.to_html()))

回答 3

我建议在上下文管理器中设置显示选项,以使其仅影响单个输出。如果您还想打印“漂亮”的html版本,我将定义一个函数并df使用force_show_all(df)以下命令显示数据框:

from IPython.core.display import display, HTML

def force_show_all(df):
    with pd.option_context('display.max_rows', None, 'display.max_columns', None, 'display.width', None):
        display(HTML(df.to_html()))

正如其他人提到的那样,请谨慎地仅在合理大小的数据帧上调用它。

I recommend setting the display options inside a context manager so that it only affects a single output. If you also want to print a “pretty” html-version, I would define a function and display the dataframe df using force_show_all(df):

from IPython.core.display import display, HTML

def force_show_all(df):
    with pd.option_context('display.max_rows', None, 'display.max_columns', None, 'display.width', None):
        display(HTML(df.to_html()))

As others have mentioned, be cautious to only call this on a reasonably-sized dataframe.


回答 4

您可以使用pandas.set_option()作为列,您可以指定以下任何选项

pd.set_option("display.max_rows", 200)
pd.set_option("display.max_columns", 100)
pd.set_option("display.max_colwidth", 200)

对于完整的打印列,您可以这样使用

import pandas as pd
pd.set_option('display.max_colwidth', -1)
print(words.head())

you can use pandas.set_option(), for column, you can specify any of these options

pd.set_option("display.max_rows", 200)
pd.set_option("display.max_columns", 100)
pd.set_option("display.max_colwidth", 200)

For full print column, you can use like this

import pandas as pd
pd.set_option('display.max_colwidth', -1)
print(words.head())


回答 5

如果要显示所有行设置如下

pd.options.display.max_rows = None

如果要显示所有列,例如波纹管

pd.options.display.max_columns = None

If you want to show all the rows set like bellow

pd.options.display.max_rows = None

If you want to show all columns set like bellow

pd.options.display.max_columns = None

ValueError:不支持的泡菜协议:3,python2泡菜无法加载python 3泡菜转储的文件?

问题:ValueError:不支持的泡菜协议:3,python2泡菜无法加载python 3泡菜转储的文件?

我使用pickle在python 3上转储文件,并使用pickle在python 2上加载文件,出现ValueError。

那么,python 2 pickle不能加载python 3 pickle丢弃的文件吗?

如果我想要吗?怎么做?

I use pickle to dump a file on python 3, and I use pickle to load the file on python 2, the ValueError appears.

So, python 2 pickle can not load the file dumped by python 3 pickle?

If I want it? How to do?


回答 0

您应该在Python 3中使用较低的协议编号来编写腌制的数据。Python3引入了一个带有该编号的新协议3(并将其用作默认协议),因此切换回2可以由Python 2读取的值。

检查中的protocol参数pickle.dump。您生成的代码将如下所示。

pickle.dump(your_object, your_file, protocol=2)

中没有protocol参数,pickle.load因为pickle可以从文件确定协议。

You should write the pickled data with a lower protocol number in Python 3. Python 3 introduced a new protocol with the number 3 (and uses it as default), so switch back to a value of 2 which can be read by Python 2.

Check the protocolparameter in pickle.dump. Your resulting code will look like this.

pickle.dump(your_object, your_file, protocol=2)

There is no protocolparameter in pickle.load because pickle can determine the protocol from the file.


回答 1

Pickle使用不同的protocols方法将您的数据转换为二进制流。

3为了能够在python 2中加载数据,您必须在python 3中指定一个低于的协议。可以protocol在调用时指定参数pickle.dump

Pickle uses different protocols to convert your data to a binary stream.

You must specify in python 3 a protocol lower than 3 in order to be able to load the data in python 2. You can specify the protocol parameter when invoking pickle.dump.


什么时候在Python中hash(n)== n?

问题:什么时候在Python中hash(n)== n?

我一直在玩Python的hash函数。对于小整数,它hash(n) == n总是出现。但是,这不会扩展为大量:

>>> hash(2**100) == 2**100
False

我并不感到惊讶,我知道哈希值取值范围有限。这个范围是多少?

我尝试使用二进制搜索来找到最小的数字hash(n) != n

>>> import codejamhelpers # pip install codejamhelpers
>>> help(codejamhelpers.binary_search)
Help on function binary_search in module codejamhelpers.binary_search:

binary_search(f, t)
    Given an increasing function :math:`f`, find the greatest non-negative integer :math:`n` such that :math:`f(n) \le t`. If :math:`f(n) > t` for all :math:`n \ge 0`, return None.

>>> f = lambda n: int(hash(n) != n)
>>> n = codejamhelpers.binary_search(f, 0)
>>> hash(n)
2305843009213693950
>>> hash(n+1)
0

2305843009213693951有什么特别之处?我注意到它小于sys.maxsize == 9223372036854775807

编辑:我正在使用Python3。我在Python 2上运行了相同的二进制搜索,得到了不同的结果2147483648,我注意到这是 sys.maxint+1

我也玩过[hash(random.random()) for i in range(10**6)]以估计哈希函数的范围。最大值始终低于上面的n。比较最小值,似乎Python 3的哈希值始终为正值,而Python 2的哈希值可以为负值。

I’ve been playing with Python’s hash function. For small integers, it appears hash(n) == n always. However this does not extend to large numbers:

>>> hash(2**100) == 2**100
False

I’m not surprised, I understand hash takes a finite range of values. What is that range?

I tried using binary search to find the smallest number hash(n) != n

>>> import codejamhelpers # pip install codejamhelpers
>>> help(codejamhelpers.binary_search)
Help on function binary_search in module codejamhelpers.binary_search:

binary_search(f, t)
    Given an increasing function :math:`f`, find the greatest non-negative integer :math:`n` such that :math:`f(n) \le t`. If :math:`f(n) > t` for all :math:`n \ge 0`, return None.

>>> f = lambda n: int(hash(n) != n)
>>> n = codejamhelpers.binary_search(f, 0)
>>> hash(n)
2305843009213693950
>>> hash(n+1)
0

What’s special about 2305843009213693951? I note it’s less than sys.maxsize == 9223372036854775807

Edit: I’m using Python 3. I ran the same binary search on Python 2 and got a different result 2147483648, which I note is sys.maxint+1

I also played with [hash(random.random()) for i in range(10**6)] to estimate the range of hash function. The max is consistently below n above. Comparing the min, it seems Python 3’s hash is always positively valued, whereas Python 2’s hash can take negative values.


回答 0

基于文件中的python文档pyhash.c

对于数字类型,数字x的哈希值是基于对x的减乘以模数质数得出的P = 2**_PyHASH_BITS - 1。它的设计使 hash(x) == hash(y)x和y在数值上相等时,即使x和y具有不同的类型。

因此,对于64/32位计算机,减少量将为2 _PyHASH_BITS -1,但是什么是_PyHASH_BITS

您可以在pyhash.h头文件中找到该文件,对于64位计算机,该头文件已定义为61(您可以在pyconfig.h文件中阅读更多说明)。

#if SIZEOF_VOID_P >= 8
#  define _PyHASH_BITS 61
#else
#  define _PyHASH_BITS 31
#endif

因此首先基于您的平台,例如在我的64位Linux平台上,减少幅度是2 61 -1,即2305843009213693951

>>> 2**61 - 1
2305843009213693951

也可以使用math.frexp来获取尾数和尾数sys.maxint,对于64位机器,该尾数和尾数表明max int为2 63

>>> import math
>>> math.frexp(sys.maxint)
(0.5, 64)

您可以通过一个简单的测试来查看差异:

>>> hash(2**62) == 2**62
True
>>> hash(2**63) == 2**63
False

阅读有关python哈希算法的完整文档https://github.com/python/cpython/blob/master/Python/pyhash.c#L34

如注释中所述,您可以使用sys.hash_info(在python 3.X中),这将为您提供用于计算哈希的参数的结构序列。

>>> sys.hash_info
sys.hash_info(width=64, modulus=2305843009213693951, inf=314159, nan=0, imag=1000003, algorithm='siphash24', hash_bits=64, seed_bits=128, cutoff=0)
>>> 

除了我在前inf几行中描述的模数之外,您还可以获得以下值:

>>> hash(float('inf'))
314159
>>> sys.hash_info.inf
314159

Based on python documentation in pyhash.c file:

For numeric types, the hash of a number x is based on the reduction of x modulo the prime P = 2**_PyHASH_BITS - 1. It’s designed so that hash(x) == hash(y) whenever x and y are numerically equal, even if x and y have different types.

So for a 64/32 bit machine, the reduction would be 2 _PyHASH_BITS – 1, but what is _PyHASH_BITS?

You can find it in pyhash.h header file which for a 64 bit machine has been defined as 61 (you can read more explanation in pyconfig.h file).

#if SIZEOF_VOID_P >= 8
#  define _PyHASH_BITS 61
#else
#  define _PyHASH_BITS 31
#endif

So first off all it’s based on your platform for example in my 64bit Linux platform the reduction is 261-1, which is 2305843009213693951:

>>> 2**61 - 1
2305843009213693951

Also You can use math.frexp in order to get the mantissa and exponent of sys.maxint which for a 64 bit machine shows that max int is 263:

>>> import math
>>> math.frexp(sys.maxint)
(0.5, 64)

And you can see the difference by a simple test:

>>> hash(2**62) == 2**62
True
>>> hash(2**63) == 2**63
False

Read the complete documentation about python hashing algorithm https://github.com/python/cpython/blob/master/Python/pyhash.c#L34

As mentioned in comment you can use sys.hash_info (in python 3.X) which will give you a struct sequence of parameters used for computing hashes.

>>> sys.hash_info
sys.hash_info(width=64, modulus=2305843009213693951, inf=314159, nan=0, imag=1000003, algorithm='siphash24', hash_bits=64, seed_bits=128, cutoff=0)
>>> 

Alongside the modulus that I’ve described in preceding lines, you can also get the inf value as following:

>>> hash(float('inf'))
314159
>>> sys.hash_info.inf
314159

回答 1

23058430092136939512^61 - 1。它是最大的Mersenne素数,适合64位。

如果您只需要将值mod取一个数字就可以进行哈希处理,那么大的Mersenne素数是一个不错的选择-它易于计算并且可以确保可能性的均匀分布。(尽管我个人永远不会这样散列)

计算浮点数的模数特别方便。它们具有将整数乘以的指数成分2^x。既然2^61 = 1 mod 2^61-1,您只需要考虑(exponent) mod 61

请参阅:https//en.wikipedia.org/wiki/Mersenne_prime

2305843009213693951 is 2^61 - 1. It’s the largest Mersenne prime that fits into 64 bits.

If you have to make a hash just by taking the value mod some number, then a large Mersenne prime is a good choice — it’s easy to compute and ensures an even distribution of possibilities. (Although I personally would never make a hash this way)

It’s especially convenient to compute the modulus for floating point numbers. They have an exponential component that multiplies the whole number by 2^x. Since 2^61 = 1 mod 2^61-1, you only need to consider the (exponent) mod 61.

See: https://en.wikipedia.org/wiki/Mersenne_prime


回答 2

哈希函数返回的是纯整数int,这意味着返回的值大于-sys.maxint和小于sys.maxint,这意味着如果传递sys.maxint + x给它,结果将为-sys.maxint + (x - 2)

hash(sys.maxint + 1) == sys.maxint + 1 # False
hash(sys.maxint + 1) == - sys.maxint -1 # True
hash(sys.maxint + sys.maxint) == -sys.maxint + sys.maxint - 2 # True

同时2**200n倍大于sys.maxint-我的猜测是,哈希将范围去了-sys.maxint..+sys.maxint,直到它停止在普通整数在这个范围内,如上面的代码段n次..

因此,通常,对于任何n <= sys.maxint

hash(sys.maxint*n) == -sys.maxint*(n%2) +  2*(n%2)*sys.maxint - n/2 - (n + 1)%2 ## True

注意:这适用于python 2。

Hash function returns plain int that means that returned value is greater than -sys.maxint and lower than sys.maxint, which means if you pass sys.maxint + x to it result would be -sys.maxint + (x - 2).

hash(sys.maxint + 1) == sys.maxint + 1 # False
hash(sys.maxint + 1) == - sys.maxint -1 # True
hash(sys.maxint + sys.maxint) == -sys.maxint + sys.maxint - 2 # True

Meanwhile 2**200 is a n times greater than sys.maxint – my guess is that hash would go over range -sys.maxint..+sys.maxint n times until it stops on plain integer in that range, like in code snippets above..

So generally, for any n <= sys.maxint:

hash(sys.maxint*n) == -sys.maxint*(n%2) +  2*(n%2)*sys.maxint - n/2 - (n + 1)%2 ## True

Note: this is true for python 2.


回答 3

可以在这里找到cpython中int类型实现。

它只返回值,除了-1,则返回-2

static long
int_hash(PyIntObject *v)
{
    /* XXX If this is changed, you also need to change the way
       Python's long, float and complex types are hashed. */
    long x = v -> ob_ival;
    if (x == -1)
        x = -2;
    return x;
}

The implementation for the int type in cpython can be found here.

It just returns the value, except for -1, than it returns -2:

static long
int_hash(PyIntObject *v)
{
    /* XXX If this is changed, you also need to change the way
       Python's long, float and complex types are hashed. */
    long x = v -> ob_ival;
    if (x == -1)
        x = -2;
    return x;
}

需要为Python 3.5.1安装urllib2

问题:需要为Python 3.5.1安装urllib2

我正在为Mac运行Python 3.5.1。我想使用urllib2模块。我尝试安装它,但被告知它已被拆分成Python 3 urllib.requesturllib.error用于Python 3。

我的命令(现在不在框架bin目录中运行,因为它不在我的路径中):

sudo ./pip3 install urllib.request

返回此:

Could not find a version that satisfies the requirement urllib.request (from versions: )
No matching distribution found for urllib.request

在尝试一口气安装之前,我遇到了同样的错误urllib2

I’m running Python 3.5.1 for Mac. I want to use urllib2 module. I tried installing it but I was told that it’s been split into urllib.request and urllib.error for Python 3.

My command (running from the framework bin directory for now because it’s not in my path):

sudo ./pip3 install urllib.request

Returns this:

Could not find a version that satisfies the requirement urllib.request (from versions: )
No matching distribution found for urllib.request

I got the same error before when I tried to install urllib2 in one fell swoop.


回答 0

警告:安全性研究发现 PyPI上多个中毒的软件包,包括名为的软件包urllib,安装后会“打电话回家”。如果您pip install urllib在2017年6月之后使用了一段时间,请尽快删除该软件包

您不能,也不需要。

urllib2是Python 2中包含的库的名称。您可以改用Python 3中包含的urllib.request。该urllib.request库的工作方式与urllib2在Python 2中的工作方式相同。由于已经包含该库,因此您无需安装它。

如果您正在遵循的教程告诉您使用方法,urllib2那么您会发现遇到更多问题。您的教程是针对Python 2编写的,而不是针对Python 3编写的。找到其他教程,或者安装Python 2.7并继续该版本的教程。您会发现urllib2该版本随附。

或者,安装该requests以获得更高级别且更易于使用的API。它可以在Python 2和3上使用。

WARNING: Security researches have found several poisoned packages on PyPI, including a package named urllib, which will ‘phone home’ when installed. If you used pip install urllib some time after June 2017, remove that package as soon as possible.

You can’t, and you don’t need to.

urllib2 is the name of the library included in Python 2. You can use the urllib.request library included with Python 3, instead. The urllib.request library works the same way urllib2 works in Python 2. Because it is already included you don’t need to install it.

If you are following a tutorial that tells you to use urllib2 then you’ll find you’ll run into more issues. Your tutorial was written for Python 2, not Python 3. Find a different tutorial, or install Python 2.7 and continue your tutorial on that version. You’ll find urllib2 comes with that version.

Alternatively, install the requests library for a higher-level and easier to use API. It’ll work on both Python 2 and 3.


回答 1

根据文档

注意 urllib2模块已拆分为Python 3中名为urllib.request和的多个模块urllib.error。将源转换为Python 3时,2to3工具将自动适应导入。

因此,似乎无法做您想做的事,但您可以使用中的适当python3函数urllib.request

Acording to the docs:

Note The urllib2 module has been split across several modules in Python 3 named urllib.request and urllib.error. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.

So it appears that it is impossible to do what you want but you can use appropriate python3 functions from urllib.request.


回答 2

在Python 3中,urllib2被两个名为urllib.request和的内置模块代替urllib.error

来源改编


因此,替换为:

import urllib2

有了这个:

import urllib.request as urllib2

In Python 3, urllib2 was replaced by two in-built modules named urllib.request and urllib.error

Adapted from source


So replace this:

import urllib2

With this:

import urllib.request as urllib2

同时安装Anacondas 2.7和3.5可以吗?

问题:同时安装Anacondas 2.7和3.5可以吗?

我目前正在将Anaconda与Python 2.7一起使用,但是我将需要使用Python 3.5。可以同时安装它们吗?我应该期待一些问题吗?
我使用的是64位Win8。

I am using currently Anaconda with Python 2.7, but I will need to use Python 3.5. Is it ok to have them installed both in the same time? Should I expect some problems?
I am on a 64-bit Win8.


回答 0

我的理解是,您无需再次安装Anaconda即可开始使用其他版本的python。相反,conda 可以单独管理python 2和3环境

My understanding is you don’t need to install Anaconda again to start using a different version of python. Instead, conda has the ability to separately manage python 2 and 3 environments.


回答 1

我会同时使用这两种方法,具体取决于我所帮助的部门(有些人喜欢2.7,有些人则喜欢3.5)。无论如何,我使用Anaconda,默认安装为3.5。我将环境用于其他版本的python,软件包等。因此,例如,当我想开始使用python 2.7时,我运行了:

 conda create -n Python27 python=2.7

这将创建一个名为Python27的新环境并安装Python版本2.7。您可以在该行中添加参数以默认情况下安装其他软件包,也可以只是从头开始。该环境将自动激活,只需在命令行中键入deactivate(windows)或source deactivate(linux,osx)即可停用。要在以后激活,请键入activate Python27(windows)或source activate Python27(linux,osx)。如果您选择采用那条路线,我建议您阅读Anaconda中的管理环境文档。

更新资料

conda4.6版开始,您现在可以使用conda activateconda deactivate。采用source现在已被弃用,最终将被删除。

I use both depending on who in my department I am helping (Some people prefer 2.7, others 3.5). Anyway, I use Anaconda and my default installation is 3.5. I use environments for other versions of python, packages, etc.. So for example, when I wanted to start using python 2.7 I ran:

 conda create -n Python27 python=2.7

This creates a new environment named Python27 and installs Python version 2.7. You can add arguments to that line for installing other packages by default or just start from scratch. The environment will automatically activate, to deactivate simply type deactivate (windows) or source deactivate (linux, osx) in the command line. To activate in the future type activate Python27 (windows) or source activate Python27 (linux, osx). I would recommend reading the documentation for Managing Environments in Anaconda, if you choose to take that route.

Update

As of conda version 4.6 you can now use conda activate and conda deactivate. The use of source is now deprecated and will eventually be removed.


回答 2

是的你可以。

您不必都下载两个Anaconda。

只有您需要下载Anaconda版本之一,并且需要激活其他版本的Anaconda python。

如果您拥有Python 3,则可以这样设置Python 2内核;

python2 -m pip install ipykernel

python2 -m ipykernel install --user

如果您有Python 2,

python3 -m pip install ipykernel

python3 -m ipykernel install --user

然后,您将能够看到两个版本的Python!

如果您正在使用Anaconda Spyder,则应在此处交换版本:

如果您使用的是木星,请在这里检查:

注意:如果安装后Jupiter或Anaconda已打开,则需要重新启动。然后您将能够看到。

Yes you can.

You don’t have to download both Anaconda.

Only you need to download one of the version of Anaconda and need activate other version of Anaconda python.

If you have Python 3, you can set up a Python 2 kernel like this;

python2 -m pip install ipykernel

python2 -m ipykernel install --user

If you have Python 2,

python3 -m pip install ipykernel

python3 -m ipykernel install --user

Then you will be able to see both version of Python!

If you are using Anaconda Spyder then you should swap version here:

If you are using Jupiter then check here:

Note: If your Jupiter or Anaconda already open after installation you need to restart again. Then you will be able to see.


回答 3

我已经安装了python 2.7.13和3.6.2。首先为python 3安装Anaconda,然后可以使用conda语法获得2.7。我的安装使用了:conda create -n py27 python = 2.7.13 anaconda

I have python 2.7.13 and 3.6.2 both installed. Install Anaconda for python 3 first and then you can use conda syntax to get 2.7. My install used: conda create -n py27 python=2.7.13 anaconda


回答 4

是的,可以同时安装两个版本。如今,实际上已经很期待了。2.7中编写了很多东西,但是3.5正在成为规范。我建议您尽快将所有python更新到3.5。

Yes, It should be alright to have both versions installed. It’s actually pretty much expected nowadays. A lot of stuff is written in 2.7, but 3.5 is becoming the norm. I would recommend updating all your python to 3.5 ASAP, though.


回答 5

Anaconda是根据您的要求制造的。它也是环境经理。它分离出环境。之所以这样做,是因为较新/不稳定的宿主语言版本不支持稳定和旧版软件包。因此,需要一种可以在同一台计算机上分离和管理这些版本的软件,而无需重新安装或卸载单个主机编程语言/环境。

您可以在Anaconda文档中找到环境的创建/删除。

希望这会有所帮助。

Anaconda is made for the purpose you are asking. It is also an environment manager. It separates out environments. It was made because stable and legacy packages were not supported with newer/unstable versions of host languages; therefore a software was required that could separate and manage these versions on the same machine without the need to reinstall or uninstall individual host programming languages/environments.

You can find creation/deletion of environments in the Anaconda documentation.

Hope this helped.