标签归档:compatibility

如何在Windows上运行多个Python版本

问题:如何在Windows上运行多个Python版本

我在计算机上安装了两个版本的Python(版本2.6和2.5)。我想为一个项目运行2.6,为另一个项目运行2.5。

如何指定我要使用哪个?

我正在使用Windows XP SP2。

I had two versions of Python installed on my machine (versions 2.6 and 2.5). I want to run 2.6 for one project and 2.5 for another.

How can I specify which I want to use?

I am working on Windows XP SP2.


回答 0

运行不同的Python副本就像启动正确的可执行文件一样容易。您提到您已经从命令行通过简单输入以下内容启动了python实例:python

这在Windows下的作用是拖曳%PATH%环境变量,检查可执行文件,无论是批处理文件(.bat),命令文件(.cmd)还是其他要运行的可执行文件(由可执行文件控制PATHEXT环境变量)是否与给定名称匹配。当找到正确的文件来运行时,该文件正在运行。

现在,如果您已经安装了两个Python版本2.5和2.6,则路径中将同时包含它们的两个目录,例如 PATH=c:\python\2.5;c:\python\2.6但是Windows将在找到匹配项时停止检查该路径。

您真正需要做的是显式调用一个或两个应用程序,例如c:\python\2.5\python.exec:\python\2.6\python.exe

另一种选择是创建一个快捷方式,以分别python.exe调用其中一个python25和另一个python26;然后python25,您只需在命令行上运行即可。

Running a different copy of Python is as easy as starting the correct executable. You mention that you’ve started a python instance, from the command line, by simply typing python.

What this does under Windows, is to trawl the %PATH% environment variable, checking for an executable, either batch file (.bat), command file (.cmd) or some other executable to run (this is controlled by the PATHEXT environment variable), that matches the name given. When it finds the correct file to run the file is being run.

Now, if you’ve installed two python versions 2.5 and 2.6, the path will have both of their directories in it, something like PATH=c:\python\2.5;c:\python\2.6 but Windows will stop examining the path when it finds a match.

What you really need to do is to explicitly call one or both of the applications, such as c:\python\2.5\python.exe or c:\python\2.6\python.exe.

The other alternative is to create a shortcut to the respective python.exe calling one of them python25 and the other python26; you can then simply run python25 on your command line.


回答 1

为该问题添加了两个解决方案:

  • 使用pylauncher(如果您使用的是Python 3.3或更高版本,则无需安装它,因为它已经随Python一起提供了),然后在脚本中添加shebang行;

#! c:\[path to Python 2.5]\python.exe-适用于要与Python 2.5一起运行
#! c:\[path to Python 2.6]\python.exe的脚本-适用于要与Python 2.6一起运行的脚本

或者代替运行python命令run pylauncher command(py)指定要使用哪个版本的Python;或者

py -2.6–版本2.6
py -2–最新安装的版本2.x
py -3.4–版本3.4
py -3–最新安装的版本3.x

virtualenv -p c:\[path to Python 2.5]\python.exe [path where you want to have virtualenv using Python 2.5 created]\[name of virtualenv]

virtualenv -p c:\[path to Python 2.6]\python.exe [path where you want to have virtualenv using Python 2.6 created]\[name of virtualenv]

例如

virtualenv -p c:\python2.5\python.exe c:\venvs\2.5

virtualenv -p c:\python2.6\python.exe c:\venvs\2.6

那么您可以激活第一个并像这样使用Python 2.5,
c:\venvs\2.5\activate
并且当您想切换到Python 2.6时,

deactivate  
c:\venvs\2.6\activate

Adding two more solutions to the problem:

  • Use pylauncher (if you have Python 3.3 or newer there’s no need to install it as it comes with Python already) and either add shebang lines to your scripts;

#! c:\[path to Python 2.5]\python.exe – for scripts you want to be run with Python 2.5
#! c:\[path to Python 2.6]\python.exe – for scripts you want to be run with Python 2.6

or instead of running python command run pylauncher command (py) specyfing which version of Python you want;

py -2.6 – version 2.6
py -2 – latest installed version 2.x
py -3.4 – version 3.4
py -3 – latest installed version 3.x

virtualenv -p c:\[path to Python 2.5]\python.exe [path where you want to have virtualenv using Python 2.5 created]\[name of virtualenv]

virtualenv -p c:\[path to Python 2.6]\python.exe [path where you want to have virtualenv using Python 2.6 created]\[name of virtualenv]

for example

virtualenv -p c:\python2.5\python.exe c:\venvs\2.5

virtualenv -p c:\python2.6\python.exe c:\venvs\2.6

then you can activate the first and work with Python 2.5 like this
c:\venvs\2.5\activate
and when you want to switch to Python 2.6 you do

deactivate  
c:\venvs\2.6\activate

回答 2

从Python 3.3开始,有适用于Windows的官方Python启动器http://www.python.org/dev/peps/pep-0397/)。现在,您也可以#!pythonX在Windows上使用来确定所需的解释器版本。在我的其他评论中查看更多详细信息或阅读PEP 397。

总结:py script.pyPython的版本中规定发布#!,如果或Python 2 #!缺失。该py -3 script.py运行Python 3。

From Python 3.3 on, there is the official Python launcher for Windows (http://www.python.org/dev/peps/pep-0397/). Now, you can use the #!pythonX to determine the wanted version of the interpreter also on Windows. See more details in my another comment or read the PEP 397.

Summary: The py script.py launches the Python version stated in #! or Python 2 if #! is missing. The py -3 script.py launches the Python 3.


回答 3

按照@alexander,您可以建立如下的符号链接集。将它们放在您的路径中包含的某个位置,以便可以轻松调用它们

> cd c:\bin
> mklink python25.exe c:\python25\python.exe
> mklink python26.exe c:\python26\python.exe

只要您将c:\ bin或您放置在其中的任何位置都在路径中,现在就可以

> python25

As per @alexander you can make a set of symbolic links like below. Put them somewhere which is included in your path so they can be easily invoked

> cd c:\bin
> mklink python25.exe c:\python25\python.exe
> mklink python26.exe c:\python26\python.exe

As long as c:\bin or where ever you placed them in is in your path you can now go

> python25

回答 4

  1. 安装python

    • C:\ Python27
    • C:\ Python36
  2. 环境变量

    • PYTHON2_HOME: C:\Python27
    • PYTHON3_HOME: C:\Python36
    • Path: %PYTHON2_HOME%;%PYTHON2_HOME%\Scripts;%PYTHON3_HOME%;%PYTHON3_HOME%\Scripts;
  3. 文件重命名

    • C:\ Python27 \ python.exe→C:\ Python27 \ python2.exe
    • C:\ Python36 \ python.exe→C:\ Python36 \ python3.exe
  4. 点子

    • python2 -m pip install package
    • python3 -m pip install package
  1. install python

    • C:\Python27
    • C:\Python36
  2. environment variable

    • PYTHON2_HOME: C:\Python27
    • PYTHON3_HOME: C:\Python36
    • Path: %PYTHON2_HOME%;%PYTHON2_HOME%\Scripts;%PYTHON3_HOME%;%PYTHON3_HOME%\Scripts;
  3. file rename

    • C:\Python27\python.exe → C:\Python27\python2.exe
    • C:\Python36\python.exe → C:\Python36\python3.exe
  4. pip

    • python2 -m pip install package
    • python3 -m pip install package

回答 5

例如对于3.6版本类型py -3.6。如果您同时具有32位和64位版本,则只需键入py -3.6-64或即可py -3.6-32

For example for 3.6 version type py -3.6. If you have also 32bit and 64bit versions, you can just type py -3.6-64 or py -3.6-32.


回答 6

当您安装Python时,它不会覆盖其他主要版本的其他安装。因此,安装Python 2.5.x不会覆盖Python 2.6.x,尽管安装2.6.6会覆盖2.6.5。

因此,您只需安装它即可。然后,调用所需的Python版本。例如:

C:\Python2.5\Python.exe

适用于Windows上的Python 2.5和

C:\Python2.6\Python.exe

适用于Windows上的Python 2.6,或

/usr/local/bin/python-2.5

要么

/usr/local/bin/python-2.6

Windows Unix(包括Linux和OS X)上。

在Unix(包括Linux和OS X)上python安装时,将安装通用命令,这是最后安装的命令。大多数情况下这不是问题,因为大多数脚本会显式调用/usr/local/bin/python2.5或一些用于防止这种情况的文件。但是,如果您不想这样做,并且您可能不想这样做,可以这样安装:

./configure
make
sudo make altinstall

请注意,“ altinstall”表示它将安装它,但不会代替python命令。

python据我所知,在Windows上您没有得到全局命令,所以这不是问题。

When you install Python, it will not overwrite other installs of other major versions. So installing Python 2.5.x will not overwrite Python 2.6.x, although installing 2.6.6 will overwrite 2.6.5.

So you can just install it. Then you call the Python version you want. For example:

C:\Python2.5\Python.exe

for Python 2.5 on windows and

C:\Python2.6\Python.exe

for Python 2.6 on windows, or

/usr/local/bin/python-2.5

or

/usr/local/bin/python-2.6

on Windows Unix (including Linux and OS X).

When you install on Unix (including Linux and OS X) you will get a generic python command installed, which will be the last one you installed. This is mostly not a problem as most scripts will explicitly call /usr/local/bin/python2.5 or something just to protect against that. But if you don’t want to do that, and you probably don’t you can install it like this:

./configure
make
sudo make altinstall

Note the “altinstall” that means it will install it, but it will not replace the python command.

On Windows you don’t get a global python command as far as I know so that’s not an issue.


回答 7

我强烈推荐pyenv-win项目。

由于kirankotari的工作,现在我们有了Windows版本的pyenv。

I strongly recommend the pyenv-win project.

Thanks to kirankotari‘s work, now we have a Windows version of pyenv.


回答 8

这是一个快速的技巧:

  1. 转到您要运行的python版本的目录
  2. 右键点击python.exe
  3. 选择“ 创建快捷方式
  4. 给该快捷方式起个呼叫的名字(我使用p27,p33等)
  5. 将该快捷方式移至您的主目录(C:\Users\Your name
  6. 打开命令提示符并输入name_of_your_shortcut.lnk(我使用p27.lnk

Here’s a quick hack:

  1. Go to the directory of the version of python you want to run
  2. Right click on python.exe
  3. Select ‘Create Shortcut
  4. Give that shortcut a name to call by( I use p27, p33 etc.)
  5. Move that shortcut to your home directory(C:\Users\Your name)
  6. Open a command prompt and enter name_of_your_shortcut.lnk(I use p27.lnk)

回答 9

cp c:\ python27 \ bin \ python.exe作为python2.7.exe

cp c:\ python34 \ bin \ python.exe作为python3.4.exe

它们都在系统路径中,请选择要运行的版本

C:\Users\username>python2.7
Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>>

C:\Users\username>python3.4
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

cp c:\python27\bin\python.exe as python2.7.exe

cp c:\python34\bin\python.exe as python3.4.exe

they are all in the system path, choose the version you want to run

C:\Users\username>python2.7
Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>>

C:\Users\username>python3.4
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

回答 10

使用批处理文件进行切换,在Windows 7上轻松高效。我使用以下命令:

在环境变量对话框(C:\ Windows \ System32 \ SystemPropertiesAdvanced.exe)中,

在用户变量部分

  1. 在路径环境变量中添加了%pathpython%

  2. 删除了对python路径的任何引用

在系统变量部分

  1. 删除了对python路径的任何引用

我为每个python安装创建了批处理文件(例如3.4 x64

名称= SetPathPython34x64 !!! ToExecuteAsAdmin.bat ;-)只是为了记住。

文件内容=

     Set PathPython=C:\Python36AMD64\Scripts\;C:\Python36AMD64\;C:\Tcl\bin

     setx PathPython %PathPython%

要在版本之间切换,我在admin模式下执行批处理文件。

!!!!! 该更改对SUBSEQUENT命令提示符窗口OPENED有效。!!!

因此,我对此有完全的控制权。

Using a batch file to switch, easy and efficient on windows 7. I use this:

In the environment variable dialog (C:\Windows\System32\SystemPropertiesAdvanced.exe),

In the section user variables

  1. added %pathpython% to the path environment variable

  2. removed any references to python pathes

In the section system variables

  1. removed any references to python pathes

I created batch files for every python installation (exmple for 3.4 x64

Name = SetPathPython34x64 !!! ToExecuteAsAdmin.bat ;-) just to remember.

Content of the file =

     Set PathPython=C:\Python36AMD64\Scripts\;C:\Python36AMD64\;C:\Tcl\bin

     setx PathPython %PathPython%

To switch between versions, I execute the batch file in admin mode.

!!!!! The changes are effective for the SUBSEQUENT command prompt windows OPENED. !!!

So I have exact control on it.


回答 11

在Windows上运行多个版本的python的最简单方法如下所述:

1)从python.org/downloads下载最新版本的python通过选择系统的相关版本,。

2)运行安装程序,然后选择将python 3.x添加到路径中以在python 3中自动设置路径(您只需单击复选框)。对于python 2,请打开python 2安装程序,选择所需的任何首选项,但只需记住将Add python.exe设置为路径将其安装在本地硬盘上,现在只需单击下一步,然后等待安装程序完成即可。

3)两个安装都完成后。右键单击我的计算机-转到属性-选择高级系统设置-转到环境变量-单击系统变量下的新建,然后添加一个新的系统变量,其变量名称PY_PYTHON并将此变量值设置为3。现在单击确定,您应该完成。

4)现在要对此进行测试,请打开命令提示符。一旦进入pythonpy,它应该打开python3

5)现在通过键入exit()退出 python3 。现在输入py -2应该会打开python 2。

如果这些都不起作用,请重新启动计算机,如果问题仍然存在,请卸载所有组件并重复步骤。

谢谢。

The easiest way to run multiple versions of python on windows is described below as follows:-

1)Download the latest versions of python from python.org/downloads by selecting the relevant version for your system.

2)Run the installer and select Add python 3.x to the path to set path automatically in python 3 (you just have to click the checkbox). For python 2 open up your python 2 installer, select whatever preferences you want but just remember to set Add python.exe to path to Will be installed on local hard drive, Now just click next and wait for the installer to finish.

3)When both the installations are complete. Right click on my computer–Go to properties–Select advanced system settings–Go to environment variables–Click on new under System variables and add a new system variable with variable name as PY_PYTHON and set this variable value to 3. Now click on OK and you should be done.

4)Now to test this open the command prompt. Once you are in there type python or py, It should open up python3.

5)Now exit out of python3 by typing exit(). Now type py -2 it should open python 2.

If none of this works then restart the computer and if the problem still persists then uninstall everything and repeat the steps.

Thanks.


回答 12

您可以从Anaconda Navigator图形化地创建不同的python开发环境。在使用不同的python版本时遇到相同的问题,因此我使用anaconda导航器创建了不同的python开发环境,并在每个环境中使用了不同的python版本。

这是帮助文档。

https://docs.anaconda.com/anaconda/navigator/tutorials/manage-environments/

You can create different python development environments graphically from Anaconda Navigator. I had same problem while working with different python versions so I used anaconda navigator to create different python development environments and used different python versions in each environments.

Here is the help documentation for this.

https://docs.anaconda.com/anaconda/navigator/tutorials/manage-environments/


回答 13

使用Rapid Environment Editor, 您可以将所需的Python安装目录推到顶部。例如,要从c:\ Python27目录启动python,请确保c:\ Python27目录在Path环境变量中的c:\ Python36目录之前或之上。根据我的经验,正在执行Path环境中找到的第一个python可执行文件。例如,我已经在Python27上安装了MSYS2,并且由于我已经将C:\ MSYS2添加到C:\ Python36之前的路径中,因此正在执行C:\ MSYS2 ….文件夹中的python.exe。

Using the Rapid Environment Editor you can push to the top the directory of the desired Python installation. For example, to start python from the c:\Python27 directory, ensure that c:\Python27 directory is before or on top of the c:\Python36 directory in the Path environment variable. From my experience, the first python executable found in the Path environment is being executed. For example, I have MSYS2 installed with Python27 and since I’ve added C:\MSYS2 to the path before C:\Python36, the python.exe from the C:\MSYS2…. folder is being executed.


回答 14

只需调用正确的可执行文件

Just call the correct executable


我可以在同一台Windows计算机上安装Python 3.x和2.x吗?

问题:我可以在同一台Windows计算机上安装Python 3.x和2.x吗?

我正在运行Windows,并且在命令行上运行程序时,shell / OS将根据注册表设置自动运行Python。如果我在同一台计算机上安装2.x和3.x版本的Python,这会中断吗?

我想玩Python 3,同时仍然能够在同一台机器上运行2.x脚本。

I’m running Windows and the shell/OS automatically runs Python based on the registry settings when you run a program on the command line. Will this break if I install a 2.x and 3.x version of Python on the same machine?

I want to play with Python 3 while still being able to run 2.x scripts on the same machine.


回答 0

共存的官方解决方案似乎是WindowsPython Launcher,PEP 397,它包含在Python 3.3.0中。将发行版转储文件py.exepyw.exe启动器安装到%SYSTEMROOT%C:\Windows)中,然后分别与pypyw脚本关联。

为了使用新启动器(无需手动设置自己的关联),请保持“注册扩展名”选项处于启用状态。我不太确定为什么,但是在我的机器上,它保留了Py 2.7作为(启动器的)“默认”值。

通过直接从命令行调用脚本来运行脚本,这些脚本将通过启动程序进行路由并解析shebang(如果存在)。您还可以显式调用启动器并使用开关:py -3 mypy2script.py

各种各样的shebangs似乎都可以工作

  • #!C:\Python33\python.exe
  • #!python3
  • #!/usr/bin/env python3

以及肆意滥用

  • #! notepad.exe

The official solution for coexistence seems to be the Python Launcher for Windows, PEP 397 which was included in Python 3.3.0. Installing the release dumps py.exe and pyw.exe launchers into %SYSTEMROOT% (C:\Windows) which is then associated with py and pyw scripts, respectively.

In order to use the new launcher (without manually setting up your own associations to it), leave the “Register Extensions” option enabled. I’m not quite sure why, but on my machine it left Py 2.7 as the “default” (of the launcher).

Running scripts by calling them directly from the command line will route them through the launcher and parse the shebang (if it exists). You can also explicitly call the launcher and use switches: py -3 mypy2script.py.

All manner of shebangs seem to work

  • #!C:\Python33\python.exe
  • #!python3
  • #!/usr/bin/env python3

as well as wanton abuses

  • #! notepad.exe

回答 1

这是我的设置:

  1. 使用Windows安装程序安装Python 2.7和3.4 。
  2. 转到C:\Python34(默认安装路径)并将python.exe更改为python3.exe
  3. 编辑 环境变量以包括C:\Python27\;C:\Python27\Scripts\;C:\Python34\;C:\Python34\Scripts\;

现在在命令行中,您可以使用python2.7和python33.4。

Here’s my setup:

  1. Install both Python 2.7 and 3.4 with the windows installers.
  2. Go to C:\Python34 (the default install path) and change python.exe to python3.exe
  3. Edit your environment variables to include C:\Python27\;C:\Python27\Scripts\;C:\Python34\;C:\Python34\Scripts\;

Now in command line you can use python for 2.7 and python3 for 3.4.


回答 2

您可以同时安装。

您应该在脚本之前编写以下代码:

#!/bin/env python2.7

或者,最终…

#!/bin/env python3.6

更新资料

Google上进行快速搜索后,我的解决方案与Unix完美搭配,这是Windows解决方案:

#!c:/Python/python3_6.exe -u

同样的事情:在脚本之前。

You can have both installed.

You should write this in front of your script:

#!/bin/env python2.7

or, eventually…

#!/bin/env python3.6

Update

My solution works perfectly with Unix, after a quick search on Google, here is the Windows solution:

#!c:/Python/python3_6.exe -u

Same thing: in front of your script.


回答 3

从3.3版开始,Python引入了适用于Windows的Launcher实用程序https://docs.python.org/3/using/windows.html#python-launcher-for-windows

为了能够使用多个版本的Python:

  1. 安装Python 2.x(x是您需要的任何版本)
  2. 安装Python 3.x(x是您需要的任何版本,您还必须拥有一个3.x> = 3.3的版本)
  3. 打开命令提示符
  4. 键入py -2.x以启动Python 2.x
  5. 键入py -3.x启动Python 3.x

From version 3.3 Python introduced Launcher for Windows utility https://docs.python.org/3/using/windows.html#python-launcher-for-windows.

So to be able to use multiple versions of Python:

  1. install Python 2.x (x is any version you need)
  2. install Python 3.x (x is any version you need also you have to have one version 3.x >= 3.3)
  3. open Command Prompt
  4. type py -2.x to launch Python 2.x
  5. type py -3.x to launch Python 3.x

回答 4

我从外壳程序中使用2.5、2.6和3.0,以及以下形式的一行批处理脚本:

:: The @ symbol at the start turns off the prompt from displaying the command.
:: The % represents an argument, while the * means all of them.
@c:\programs\pythonX.Y\python.exe %*

命名它们pythonX.Y.bat并将它们放在PATH中的某个位置。将首选的次要版本(即最新版本)的文件复制到pythonX.bat。(例如copy python2.6.bat python2.bat。)然后您可以python2 file.py在任何地方使用。

但是,这没有帮助甚至影响Windows文件关联的情况。为此,您需要一个启动器程序来读取该#!行,然后将其与.py和.pyw文件关联。

I’m using 2.5, 2.6, and 3.0 from the shell with one line batch scripts of the form:

:: The @ symbol at the start turns off the prompt from displaying the command.
:: The % represents an argument, while the * means all of them.
@c:\programs\pythonX.Y\python.exe %*

Name them pythonX.Y.bat and put them somewhere in your PATH. Copy the file for the preferred minor version (i.e. the latest) to pythonX.bat. (E.g. copy python2.6.bat python2.bat.) Then you can use python2 file.py from anywhere.

However, this doesn’t help or even affect the Windows file association situation. For that you’ll need a launcher program that reads the #! line, and then associate that with .py and .pyw files.


回答 5

将两者都添加到环境变量时,将发生冲突,因为两个可执行文件具有相同的名称:python.exe

只需重命名其中之一即可。就我而言,我将其重命名为python3.exe

因此,当我运行python它将执行python.exe2.7,而当我运行python3将执行python3.exe3.6

When you add both to environment variables there will a be a conflict because the two executable have the same name: python.exe.

Just rename one of them. In my case I renamed it to python3.exe.

So when I run python it will execute python.exe which is 2.7 and when I run python3 it will execute python3.exe which is 3.6


回答 6

干得好…

winpylaunch.py

#
# Looks for a directive in the form: #! C:\Python30\python.exe
# The directive must start with #! and contain ".exe".
# This will be assumed to be the correct python interpreter to
# use to run the script ON WINDOWS. If no interpreter is
# found then the script will be run with 'python.exe'.
# ie: whatever one is found on the path.
# For example, in a script which is saved as utf-8 and which
# runs on Linux and Windows and uses the Python 2.6 interpreter...
#
#    #!/usr/bin/python
#    #!C:\Python26\python.exe
#    # -*- coding: utf-8 -*-
#
# When run on Linux, Linux uses the /usr/bin/python. When run
# on Windows using winpylaunch.py it uses C:\Python26\python.exe.
#
# To set up the association add this to the registry...
#
#    HKEY_CLASSES_ROOT\Python.File\shell\open\command
#    (Default) REG_SZ = "C:\Python30\python.exe" S:\usr\bin\winpylaunch.py "%1" %*
#
# NOTE: winpylaunch.py itself works with either 2.6 and 3.0. Once
# this entry has been added python files can be run on the
# commandline and the use of winpylaunch.py will be transparent.
#

import subprocess
import sys

USAGE = """
USAGE: winpylaunch.py <script.py> [arg1] [arg2...]
"""

if __name__ == "__main__":
  if len(sys.argv) > 1:
    script = sys.argv[1]
    args   = sys.argv[2:]
    if script.endswith(".py"):
      interpreter = "python.exe" # Default to wherever it is found on the path.
      lines = open(script).readlines()
      for line in lines:
        if line.startswith("#!") and line.find(".exe") != -1:
          interpreter = line[2:].strip()
          break
      process = subprocess.Popen([interpreter] + [script] + args)
      process.wait()
      sys.exit()
  print(USAGE)

我刚刚在阅读此线程时就搞定了(因为这也是我所需要的)。我在Ubuntu和Windows上都有Python 2.6.1和3.0.1。如果对您不起作用,请在此处发布修复程序。

Here you go…

winpylaunch.py

#
# Looks for a directive in the form: #! C:\Python30\python.exe
# The directive must start with #! and contain ".exe".
# This will be assumed to be the correct python interpreter to
# use to run the script ON WINDOWS. If no interpreter is
# found then the script will be run with 'python.exe'.
# ie: whatever one is found on the path.
# For example, in a script which is saved as utf-8 and which
# runs on Linux and Windows and uses the Python 2.6 interpreter...
#
#    #!/usr/bin/python
#    #!C:\Python26\python.exe
#    # -*- coding: utf-8 -*-
#
# When run on Linux, Linux uses the /usr/bin/python. When run
# on Windows using winpylaunch.py it uses C:\Python26\python.exe.
#
# To set up the association add this to the registry...
#
#    HKEY_CLASSES_ROOT\Python.File\shell\open\command
#    (Default) REG_SZ = "C:\Python30\python.exe" S:\usr\bin\winpylaunch.py "%1" %*
#
# NOTE: winpylaunch.py itself works with either 2.6 and 3.0. Once
# this entry has been added python files can be run on the
# commandline and the use of winpylaunch.py will be transparent.
#

import subprocess
import sys

USAGE = """
USAGE: winpylaunch.py <script.py> [arg1] [arg2...]
"""

if __name__ == "__main__":
  if len(sys.argv) > 1:
    script = sys.argv[1]
    args   = sys.argv[2:]
    if script.endswith(".py"):
      interpreter = "python.exe" # Default to wherever it is found on the path.
      lines = open(script).readlines()
      for line in lines:
        if line.startswith("#!") and line.find(".exe") != -1:
          interpreter = line[2:].strip()
          break
      process = subprocess.Popen([interpreter] + [script] + args)
      process.wait()
      sys.exit()
  print(USAGE)

I’ve just knocked this up on reading this thread (because it’s what I was needing too). I have Pythons 2.6.1 and 3.0.1 on both Ubuntu and Windows. If it doesn’t work for you post fixes here.


回答 7

据我所知,Python使用PATH变量而不是注册表设置来从命令行运行。

因此,如果您在PATH上指向正确的版本,则将使用该版本。请记住,重新启动命令提示符以使用新的PATH设置。

As far as I know Python runs off of the commandline using the PATH variable as opposed to a registry setting.

So if you point to the correct version on your PATH you will use that. Remember to restart your command prompt to use the new PATH settings.


回答 8

Python安装通常会将.py.pyw.pyc文件与Python解释器相关联。因此,您可以通过在资源管理器中双击Python脚本或在命令行窗口中键入其名称来运行Python脚本(这样就无需键入python scriptname.py,就scriptname.py可以了)。

如果要手动更改此关联,则可以在Windows注册表中编辑以下项:

HKEY_CLASSES_ROOT\Python.File\shell\open\command
HKEY_CLASSES_ROOT\Python.NoConFile\shell\open\command
HKEY_CLASSES_ROOT\Python.CompiledFile\shell\open\command

Python启动器

人们一直在研究Windows的Python启动器:与.py.pyw文件相关联的轻量级程序,它将在第一行中寻找“ shebang”行(类似于Linux等),并以2.x或3.x版本启动Python。需要。有关详细信息,请参见“适用于Windows的Python启动器”博客文章。

The Python installation normally associates .py, .pyw and .pyc files with the Python interpreter. So you can run a Python script either by double-clicking it in Explorer or by typing its name in a command-line window (so no need to type python scriptname.py, just scriptname.py will do).

If you want to manually change this association, you can edit these keys in the Windows registry:

HKEY_CLASSES_ROOT\Python.File\shell\open\command
HKEY_CLASSES_ROOT\Python.NoConFile\shell\open\command
HKEY_CLASSES_ROOT\Python.CompiledFile\shell\open\command

Python Launcher

People have been working on a Python launcher for Windows: a lightweight program associated with .py and .pyw files which would look for a “shebang” line (similar to Linux et al) on the first line, and launch Python 2.x or 3.x as required. See “A Python Launcher for Windows” blog post for details.


回答 9

尝试使用Anaconda。

假设使用Anaconda环境的概念,您需要Python 3来学习编程,但是您不想通过更新Python来消灭Python 2.7环境。您可以创建并激活名为“ snakes”(或所需的任何名称)的新环境,并按如下所示安装最新版本的Python 3:

conda create --name snakes python=3

它比听起来简单,请在此处查看介绍页面:Anaconda入门

然后要解决并排运行2.x和3.x版本的特定问题,请参阅:使用Anaconda管理Python版本

Try using Anaconda.

Using the concept of Anaconda environments, let’s say you need Python 3 to learn programming, but you don’t want to wipe out your Python 2.7 environment by updating Python. You can create and activate a new environment named “snakes” (or whatever you want), and install the latest version of Python 3 as follows:

conda create --name snakes python=3

Its simpler than it sounds, take a look at the intro page here: Getting Started with Anaconda

And then to handle your specific problem of having version 2.x and 3.x running side by side, see:


回答 10

这是在同一台机器上运行Python 2和3的方法

  1. 安装Python 2.x
  2. 安装Python 3.x
  3. 启动Powershell
  4. 输入Python -2以启动Python 2.x
  5. 输入Python -3启动Python 2.x

WindowsPython启动器自3.3版开始嵌入到Python中,正如2011年Stand Stand首次亮相时所承诺的那样:

适用于Windows的Python启动器

Here is how to run Python 2 and 3 on the same machine

  1. install Python 2.x
  2. install Python 3.x
  3. Start Powershell
  4. Type Python -2 to launch Python 2.x
  5. Type Python -3 to launch Python 2.x

The Python Launcher for Windows was embedded into Python since Version 3.3, as promised in 2011 when the Stand alone first made its debut:

Python Launcher for Windows


回答 11

这是在Windows上安装Python2和Python3的一种简洁方法。

https://datascience.com.co/how-to-install-python-2-7-and-3-6-in-windows-10-add-python-path-281e7eae62a

我的情况:我必须安装Apache cassandra。我已经在D:驱动器中安装了Python3 。随着大量开发工作的进行,我不想弄乱我的Python3安装。而且,我只需要Python2用于Apache cassandra。

所以我采取了以下步骤:

  1. 下载并安装了Python2。
  2. 已将Python2条目添加到类路径(C:\Python27;C:\Python27\Scripts
  3. python.exe修改为python2.exe(如下图所示)

  1. 现在我可以同时运行两者。适用于Python 2(python2 --version)和Python 3(python --version)。

因此,我的Python3安装保持不变。

Here is a neat and clean way to install Python2 & Python3 on windows.

https://datascience.com.co/how-to-install-python-2-7-and-3-6-in-windows-10-add-python-path-281e7eae62a

My case: I had to install Apache cassandra. I already had Python3 installed in my D: drive. With loads of development work under process i didn’t wanted to mess my Python3 installation. And, i needed Python2 only for Apache cassandra.

So i took following steps:

  1. Downloaded & Installed Python2.
  2. Added Python2 entries to classpath (C:\Python27;C:\Python27\Scripts)
  3. Modified python.exe to python2.exe (as shown in image below)

  1. Now i am able to run both. For Python 2(python2 --version) & Python 3 (python --version).

So, my Python3 installation remained intact.


回答 12

我认为可以在安装程序中为.py文件设置Windows文件关联。取消选中它就可以了。

如果没有,您可以轻松地将.py文件与以前的版本重新关联。最简单的方法是右键单击.py文件,选择“打开方式” /“选择程序”。在出现的对话框中,选择或浏览到默认情况下要使用的python版本,然后选中“始终使用此程序打开这种文件”复选框。

I think there is an option to setup the windows file association for .py files in the installer. Uncheck it and you should be fine.

If not, you can easily re-associate .py files with the previous version. The simplest way is to right click on a .py file, select “open with” / “choose program”. On the dialog that appears, select or browse to the version of python you want to use by default, and check the “always use this program to open this kind of file” checkbox.


回答 13

您应该确保PATH环境变量不包含两个python.exe文件(添加您当前用于每天运行脚本的文件),或按照批处理文件的建议进行操作。除此之外,我不明白为什么不这样。

PS:我安装了2.6作为“主要” python,安装了3.0作为“ play” python。2.6包含在PATH中。一切正常。

You should make sure that the PATH environment variable doesn’t contain both python.exe files ( add the one you’re currently using to run scripts on a day to day basis ) , or do as Kniht suggested with the batch files . Aside from that , I don’t see why not .

P.S : I have 2.6 installed as my “primary” python and 3.0 as my “play” python . The 2.6 is included in the PATH . Everything works fine .


回答 14

在我勇敢地同时安装两者之前,我有很多问题。如果我给python,我要py2时会转到py3吗?pip / virtualenv是否会在py2 / 3下发生?

现在看来非常简单。

只需盲目安装它们。确保您获得正确的类型(x64 / x32)。在安装时/安装后,请确保添加到环境变量的路径。

[ENVIRONMENT]::SETENVIRONMENTVARIABLE("PATH", "$ENV:PATH;C:\PYTHONx", "USER")

替换上面命令中的x以设置路径。

然后转到两个文件夹。

导航

python3.6/Scripts/

并将pip重命名为pip3。

如果pip3已经存在,请删除该pip。这将确保just pip将在python2下运行。您可以通过以下方式进行验证:

pip --version

如果您想在python3中使用pip,请使用

pip3 install 

您可以类似地对python文件和其他文件执行相同的操作。

干杯!

Before I courageously installed both simultaneously, I had so many questions. If I give python will it go to py3 when i want py2? pip/virtualenv will happen under py2/3?

It seems to be very simple now.

Just blindly install both of them. Make sure you get the right type(x64/x32). While/after installing make sure you add to the path to your environment variables.

[ENVIRONMENT]::SETENVIRONMENTVARIABLE("PATH", "$ENV:PATH;C:\PYTHONx", "USER")

Replace the x in the command above to set the path.

Then go to both the folders.

Navigate to

python3.6/Scripts/

and rename pip to pip3.

If pip3 already exists delete the pip. This will make sure that just pip will run under python2. You can verify by:

pip --version

In case you want to use pip with python3 then just use

pip3 install 

You can similarly do the same to python file and others.

Cheers!


回答 15

Easy-peasy,在安装了两个python版本之后,将路径添加到环境变量;请参阅。然后转到python 2和python 3文件夹,分别将它们重命名为python2和python3,如图和所示。现在在cmd中键入python2或python3以使用所需的版本,请参见

Easy-peasy ,after installing both the python versions add the paths to the environment variables ;see. Then go to python 2 and python 3 folders and rename them to python2 and python3 respectively as shown and . Now in cmd type python2 or python3 to use your required version see .


回答 16

我假设是这样,我在同一台计算机上并排安装了Python 2.4、2.5和2.6。

I would assume so, I have Python 2.4, 2.5 and 2.6 installed side-by-side on the same computer.


回答 17

我现在刚开始使用python。我正在阅读Zed Shaw的书“以困难的方式学习Python”,该书需要python 2.x版本,但同时也要学习一个需要python 3.x的类。

这就是我所做的。

  1. 下载python 2.7
  2. 运行电源外壳(应该已经在Windows上安装)
  3. 在POWERSHELL中运行python(如果无法识别,请转到步骤4)
  4. 仅当powershell无法识别python 2.7时,才输入以下内容:

“ [[环境] :: SETENVIRONMENTVARIABLE(“ PATH”,“ $ ENV:PATH; C:\ PYTHON27”,“ USER”)“(无外部引号)

  1. 现在键入python,您应该看到它说python 2.7等等等等

现在适用于python 3.x

简单,适用于Windows应用程序的python 3.x下载带有python。因此,只需将适用于Windows的Python应用程序固定到任务栏,或创建桌面快捷方式即可完成!

打开适用于Windows的3.x版Python

打开适用于python 2.x的Powershell

我希望这有帮助!

I am just starting out with python now. I’m reading Zed Shaw’s book “Learn Python the Hard Way” which requires python version 2.x but am also taking a class that requires python 3.x

So here is what I did.

  1. Download python 2.7
  2. run power shell (should already be installed on windows)
  3. run python IN POWERSHELL (if it doesn’t recognize then go to step 4)
  4. Only if powershell doesn’t recognize python 2.7 type in the following:

“[ENVIRONMENT]::SETENVIRONMENTVARIABLE(“PATH”, “$ENV:PATH;C:\PYTHON27”, “USER”)” (no outside quotes)

  1. Now type python and you should see it say python 2.7 blah blah blah

NOW for python 3.x

Simple, python 3.x download comes with python for windows app. SO simply pin the Python for Windows app to your task bar, or create shortcut to the desktop and you are done!

Open Python for Windows for 3.x

Open Powershell for python 2.x

I hope this helps!


回答 18

嗯..我现在通过在https://www.python.org/downloads/release/python-365/下载适用于Windows的Python 3.6.5来做到这一点,并确保将安装启动器。然后,我按照使用python 2和python 3的说明进行操作。重新启动命令提示符,然后使用py -2.7来使用Python 2和pypy -3.6来使用Python3。您还可以将其pip2用于Python 2 pippipPython 3 pip

Hmm..I did this right now by just downloading Python 3.6.5 for Windows at https://www.python.org/downloads/release/python-365/ and made sure that the launcher would be installed. Then, I followed the instructions for using python 2 and python 3. Restart the command prompt and then use py -2.7 to use Python 2 and py or py -3.6 to use Python 3. You can also use pip2 for Python 2’s pip and pip for Python 3’s pip.


回答 19

我在要使用python3进行大多数工作时遇到了同样的问题,但是IDA pro需要python2。所以,这就是我所做的。

我首先在用户环境变量中创建了3个变量,如下所示:

  1. PYTHON_ACTIVE:最初为空
  2. HOME_PYTHON27:具有安装Python 2的文件夹的路径。例如。“; /脚本;”
  3. HOME_PYTHON38:类似于python 2,此变量包含python 3文件夹的路径。

现在我加了

%PYTHON_ACTIVE%

到PATH变量。因此,基本上说这个“ PYTHON_ACTIVE”包含的内容就是活动的python。我们以编程方式更改“ PYTHON_ACTIVE”的包含内容以切换python版本。

这是示例脚本:

:: This batch file is used to switch between python 2 and 3.
@ECHO OFF

set /p choice= "Please enter '27' for python 2.7 , '38' for python 3.8 : "

IF %choice%==27 (
setx PYTHON_ACTIVE %HOME_PYTHON27%
)

IF %choice%==38 (
setx PYTHON_ACTIVE %HOME_PYTHON38%
)


PAUSE

该脚本将python版本作为输入,并因此将HOME_PYTHON27或HOME_PYTHON38复制到PYTHON_ACTIVE。从而更改了全局Python版本。

I had the same problem where I wanted to use python3 for most work but IDA pro required python2. SO, here’s what I did.

I first created 3 variables in the user environment variable as follows:

  1. PYTHON_ACTIVE : This is initially empty
  2. HOME_PYTHON27 : Has a path to a folder where Python 2 is installed. Eg. “;/scripts;”
  3. HOME_PYTHON38 : Similar to python 2, this variable contains a path to python 3 folders.

Now I added

%PYTHON_ACTIVE%

to PATH variable. So, basically saying that whatever this “PYTHON_ACTIVE” contains is the active python. We programmatically change the contains of “PYTHON_ACTIVE” to switch python version.

Here is the example script:

:: This batch file is used to switch between python 2 and 3.
@ECHO OFF

set /p choice= "Please enter '27' for python 2.7 , '38' for python 3.8 : "

IF %choice%==27 (
setx PYTHON_ACTIVE %HOME_PYTHON27%
)

IF %choice%==38 (
setx PYTHON_ACTIVE %HOME_PYTHON38%
)


PAUSE

This script takes python version as input and accordingly copies HOME_PYTHON27 or HOME_PYTHON38 to PYTHON_ACTIVE. Thus changing the global Python version.


如何将字典转换为元组列表?

问题:如何将字典转换为元组列表?

如果我有这样的字典:

{ 'a': 1, 'b': 2, 'c': 3 }

如何将其转换为此?

[ ('a', 1), ('b', 2), ('c', 3) ]

以及如何将其转换为此?

[ (1, 'a'), (2, 'b'), (3, 'c') ]

If I have a dictionary like:

{ 'a': 1, 'b': 2, 'c': 3 }

How can I convert it to this?

[ ('a', 1), ('b', 2), ('c', 3) ]

And how can I convert it to this?

[ (1, 'a'), (2, 'b'), (3, 'c') ]

回答 0

>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> d.items()
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v, k) for k, v in d.iteritems()]
[(1, 'a'), (3, 'c'), (2, 'b')]

它不是您想要的顺序,但是字典始终没有任何特定的顺序。1对其进行排序或根据需要进行组织。

参见:items()iteritems()


在Python 3.x中,您将不使用iteritems(不再存在),而使用items,它现在返回字典项目的“视图”。看到什么新的Python 3.0文档,以及新的看法文档

1:在Python 3.7中添加了字典的插入顺序保留

>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> d.items()
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v, k) for k, v in d.iteritems()]
[(1, 'a'), (3, 'c'), (2, 'b')]

It’s not in the order you want, but dicts don’t have any specific order anyway.1 Sort it or organize it as necessary.

See: items(), iteritems()


In Python 3.x, you would not use iteritems (which no longer exists), but instead use items, which now returns a “view” into the dictionary items. See the What’s New document for Python 3.0, and the new documentation on views.

1: Insertion-order preservation for dicts was added in Python 3.7


回答 1

因为没有其他人做过,所以我将添加py3k版本:

>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> list(d.items())
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v, k) for k, v in d.items()]
[(1, 'a'), (3, 'c'), (2, 'b')]

since no one else did, I’ll add py3k versions:

>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> list(d.items())
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v, k) for k, v in d.items()]
[(1, 'a'), (3, 'c'), (2, 'b')]

回答 2

您可以使用列表推导。

[(k,v) for k,v in a.iteritems()] 

会得到你[ ('a', 1), ('b', 2), ('c', 3) ]

[(v,k) for k,v in a.iteritems()] 

另一个例子。

如果愿意,请阅读有关列表理解的更多信息,您可以使用它们来做非常有趣。

You can use list comprehensions.

[(k,v) for k,v in a.iteritems()] 

will get you [ ('a', 1), ('b', 2), ('c', 3) ] and

[(v,k) for k,v in a.iteritems()] 

the other example.

Read more about list comprehensions if you like, it’s very interesting what you can do with them.


回答 3

创建一个namedtuple列表

使用namedtuple通常很方便。例如,您有一个“名称”作为键,而“分数”作为值的字典,例如:

d = {'John':5, 'Alex':10, 'Richard': 7}

您可以将项目列为元组,根据需要进行排序,并获得名称和分数,比如说Python得分最高(index = 0)的玩家非常Python化,如下所示:

>>> player = best[0]

>>> player.name
        'Alex'
>>> player.score
         10

这该怎么做:

以随机顺序或保持collections.OrderedDict的顺序列出:

import collections
Player = collections.namedtuple('Player', 'name score')
players = list(Player(*item) for item in d.items())

按值(“分数”)排序:

import collections
Player = collections.namedtuple('Player', 'score name')

首先以最低分数排序:

worst = sorted(Player(v,k) for (k,v) in d.items())

首先以最高分排序:

best = sorted([Player(v,k) for (k,v) in d.items()], reverse=True)

Create a list of namedtuples

It can often be very handy to use namedtuple. For example, you have a dictionary of ‘name’ as keys and ‘score’ as values like:

d = {'John':5, 'Alex':10, 'Richard': 7}

You can list the items as tuples, sorted if you like, and get the name and score of, let’s say the player with the highest score (index=0) very Pythonically like this:

>>> player = best[0]

>>> player.name
        'Alex'
>>> player.score
         10

How to do this:

list in random order or keeping order of collections.OrderedDict:

import collections
Player = collections.namedtuple('Player', 'name score')
players = list(Player(*item) for item in d.items())

in order, sorted by value (‘score’):

import collections
Player = collections.namedtuple('Player', 'score name')

sorted with lowest score first:

worst = sorted(Player(v,k) for (k,v) in d.items())

sorted with highest score first:

best = sorted([Player(v,k) for (k,v) in d.items()], reverse=True)

回答 4

你想要的是dictitems()iteritems()方法。items返回(键,值)元组的列表。由于元组是不可变的,因此它们不能反转。因此,您必须迭代这些项并创建新的元组,以获取反转的(值,键)元组。对于迭代而言,iteritems是首选方法,因为它使用生成器来生成(键,值)元组,而不必将整个列表保留在内存中。

Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = { 'a': 1, 'b': 2, 'c': 3 }
>>> a.items()
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v,k) for (k,v) in a.iteritems()]
[(1, 'a'), (3, 'c'), (2, 'b')]
>>> 

What you want is dict‘s items() and iteritems() methods. items returns a list of (key,value) tuples. Since tuples are immutable, they can’t be reversed. Thus, you have to iterate the items and create new tuples to get the reversed (value,key) tuples. For iteration, iteritems is preferable since it uses a generator to produce the (key,value) tuples rather than having to keep the entire list in memory.

Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = { 'a': 1, 'b': 2, 'c': 3 }
>>> a.items()
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v,k) for (k,v) in a.iteritems()]
[(1, 'a'), (3, 'c'), (2, 'b')]
>>> 

回答 5

[(k,v) for (k,v) in d.iteritems()]

[(v,k) for (k,v) in d.iteritems()]
[(k,v) for (k,v) in d.iteritems()]

and

[(v,k) for (k,v) in d.iteritems()]

回答 6

这些是Python 3.x和Python 2.x的重大变化

对于Python3.x使用

dictlist = []
for key, value in dict.items():
    temp = [key,value]
    dictlist.append(temp)

对于Python 2.7使用

dictlist = []
for key, value in dict.iteritems():
    temp = [key,value]
    dictlist.append(temp)

These are the breaking changes from Python 3.x and Python 2.x

For Python3.x use

dictlist = []
for key, value in dict.items():
    temp = [key,value]
    dictlist.append(temp)

For Python 2.7 use

dictlist = []
for key, value in dict.iteritems():
    temp = [key,value]
    dictlist.append(temp)

回答 7

>>> a = {'a':1,'b':2,'c':3}

>>> [[x,a [x])for a.keys()中的x]
[('a',1),('c',3),('b',2)]

>>> [[(a [x],x)for a.keys()中的x]
[(1,'a'),(3,'c'),(2,'b')]
>>> a={ 'a': 1, 'b': 2, 'c': 3 }

>>> [(x,a[x]) for x in a.keys() ]
[('a', 1), ('c', 3), ('b', 2)]

>>> [(a[x],x) for x in a.keys() ]
[(1, 'a'), (3, 'c'), (2, 'b')]

回答 8

通过keys()values()字典的方法和zip

zip 将返回一个类似于有序字典的元组列表。

演示:

>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> zip(d.keys(), d.values())
[('a', 1), ('c', 3), ('b', 2)]
>>> zip(d.values(), d.keys())
[(1, 'a'), (3, 'c'), (2, 'b')]

By keys() and values() methods of dictionary and zip.

zip will return a list of tuples which acts like an ordered dictionary.

Demo:

>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> zip(d.keys(), d.values())
[('a', 1), ('c', 3), ('b', 2)]
>>> zip(d.values(), d.keys())
[(1, 'a'), (3, 'c'), (2, 'b')]

回答 9

d = {'John':5, 'Alex':10, 'Richard': 7}
list = []
for i in d:
   k = (i,d[i])
   list.append(k)

print list
d = {'John':5, 'Alex':10, 'Richard': 7}
list = []
for i in d:
   k = (i,d[i])
   list.append(k)

print list

回答 10

一个简单的是

list(dictionary.items())  # list of (key, value) tuples
list(zip(dictionary.values(), dictionary.keys()))  # list of (key, value) tuples

第二个不是更简单,而是。

A simpler one would be

list(dictionary.items())  # list of (key, value) tuples
list(zip(dictionary.values(), dictionary.keys()))  # list of (key, value) tuples

如何在Windows中同时安装Python 2.x和Python 3.x

问题:如何在Windows中同时安装Python 2.x和Python 3.x

我在Windows 7上使用Python 3.x进行大部分编程,但是现在我需要使用Python Imaging Library(PIL),ImageMagick和wxPython,所有这些都需要Python2.x。

我可以在Windows 7中同时安装Python 2.x和Python 3.x吗?运行脚本时,如何“选择”应该运行哪个版本的Python?前面提到的程序能否处理一次安装的多个版本的Python?我已经搜索了数小时,但无济于事。

谢谢。

I do most of my programming in Python 3.x on Windows 7, but now I need to use the Python Imaging Library (PIL), ImageMagick, and wxPython, all of which require Python 2.x.

Can I have both Python 2.x and Python 3.x installed in Windows 7? When I run a script, how would I “choose” which version of Python should run it? Will the aforementioned programs be able to handle multiple versions of Python installed at once? I have searched for hours and hours for how to do this to no avail.

Thanks.


回答 0

我发现执行此操作的正式方法如下:

只需在Windows 7上安装两个(或多个,使用其安装程序)Python版本(对我来说,使用3.3和2.7)。

请遵循以下指示,根据需要更改参数。

创建以下环境变量(默认为双击):

Name:  PY_PYTHON
Value: 3

要在特定的解释器中启动脚本,请添加以下shebang(脚本开始):

#! python2

要使用特定的解释器执行脚本,请使用以下提示命令:

> py -2 MyScript.py

要启动特定的解释器:

> py -2

要启动默认解释器(由PY_PYTHON变量定义):

> py

资源资源

文档:在Windows上使用Python

PEP 397-适用于Windows的Python启动器

I found that the formal way to do this is as follows:

Just install two (or more, using their installers) versions of Python on Windows 7 (for me work with 3.3 and 2.7).

Follow the instuctions below, changing the parameters for your needs.

Create the following environment variable (to default on double click):

Name:  PY_PYTHON
Value: 3

To launch a script in a particular interpreter, add the following shebang (beginning of script):

#! python2

To execute a script using a specific interpreter, use the following prompt command:

> py -2 MyScript.py

To launch a specific interpreter:

> py -2

To launch the default interpreter (defined by the PY_PYTHON variable):

> py

Resources

Documentation: Using Python on Windows

PEP 397 – Python launcher for Windows


回答 1

我所做的是下载了2.7.6和3.3.4。Python 3.3.4可以选择在环境变量中添加路径。所以基本上我只是手动添加了Python 2.7.6。

如何…

  1. 开始>在环境中的搜索类型中,选择“将环境变量编辑到您的帐户” 1

  2. 向下滚动到路径,选择路径,然后单击编辑。

  3. 添加C:\ Python27; 因此,您应该在那里拥有两个版本的Python的路径,但是如果没有,则可以轻松地对其进行编辑,以便您执行….. C:\ Python27; C:\ Python33;

  4. 导航到C:\中的Python27文件夹,并将python.exe的副本重命名为python2.exe

  5. 导航到C:\中的Python34文件夹,并将python.exe的副本重命名为python3.exe

  6. 测试:打开命令提示符并输入python2 …. BOOM!Python 2.7.6。退出。

  7. 测试:打开命令提示符并输入python3 …. BOOM!Python 3.4.3。退出。

注意:(为了避免在第4步和第5步中破坏pip命令,请将python.exe的副本保留在与重命名文件相同的目录中)

What I did was download both 2.7.6 and 3.3.4. Python 3.3.4 has the option to add the path to it in the environment variable so that was done. So basically I just manually added Python 2.7.6.

How to…

  1. Start > in the search type in environment select “Edit environment variables to your account”1

  2. Scroll down to Path, select path, click edit.

  3. Add C:\Python27; so you should have paths to both versions of Python there, but if you don’t this you can easily edit it so that you do….. C:\Python27;C:\Python33;

  4. Navigate to the Python27 folder in C:\ and rename a copy of python.exe to python2.exe

  5. Navigate to the Python34 folder in C:\ and rename a copy of python.exe to python3.exe

  6. Test: open up commmand prompt and type python2 ….BOOM! Python 2.7.6. exit out.

  7. Test: open up commmand prompt and type python3 ….BOOM! Python 3.4.3. exit out.

Note: (so as not to break pip commands in step 4 and 5, keep copy of python.exe in the same directory as the renamed file)


回答 2

我在Windows中有多个版本。我只是更改了非默认版本的exe名称。

python.exe-> python26.exe

pythonw.exe-> pythonw26.exe

至于软件包安装程序,大多数exe安装程序都允许您选择python安装来添加软件包。对于手动安装,请检查–prefix选项以定义软件包的安装位置:

http://docs.python.org/install/index.html#alternate-installation-windows-the-prefix-scheme

I have multiple versions in windows. I just change the exe name of the version I’m not defaulting to.

python.exe –> python26.exe

pythonw.exe –> pythonw26.exe

As for package installers, most exe installers allow you to choose the python install to add the package too. For manual installation check out the –prefix option to define where the package should be installed:

http://docs.python.org/install/index.html#alternate-installation-windows-the-prefix-scheme


回答 3

如果使用Anaconda Python,则可以轻松安装各种环境。

假设您已安装Anaconda Python 2.7,并且想要一个Python 3.4环境:

conda create -n py34 python=3.4 anaconda

然后激活环境:

activate py34

并停用:

deactivate py34

(对于Linux,您应该使用 source activate py34。)

链接:

下载Anaconda Python

环境说明

If you use Anaconda Python, you can easily install various environments.

Say you had Anaconda Python 2.7 installed and you wanted a python 3.4 environment:

conda create -n py34 python=3.4 anaconda

Then to activate the environment:

activate py34

And to deactive:

deactivate py34

(With Linux, you should use source activate py34.)

Links:

Download Anaconda Python

Instructions for environments


回答 4

要在同一系统中安装和运行任何版本的Python,请遵循以下指南。


例如,说您想在同一Windows系统上安装Python 2.x和Python3.x。

  1. 在需要的任何位置安装它们的两个二进制发行版。

    • 出现提示时,请勿注册其文件扩展名和
    • 不要将它们自动添加到PATH环境变量中
  2. 仅运行命令python,便会选择要在PATH中首次遇到的可执行文件进行启动。换句话说,手动添加Python目录。键入时,将选择第一个添加的对象python。像这样选择连续的python程序(将其目录放置在PATH中的顺序增加):

    • py -2第二 python
    • py -3表示第三个python等等。
  3. 无论“ pythons”的顺序如何,您都可以:

    • 使用以下命令运行Python 2.x脚本:py -2(Python 3.x功能)(即,将选择在PATH中找到的第一个Python 2.x安装程序)
    • 使用以下命令运行Python 3.x脚本:或py -3(即,将选择在PATH中找到的第一个Python 3.x安装程序)

在我的示例中,我先安装了Python 2.7.14,然后安装了Python 3.5.3。这是我的PATH变量以以下内容开头的方式:

PATH = C:\ Program Files \ Microsoft MPI \ Bin \; C:\ Python27; C:\ Program Files \ Python_3.6 \ Scripts \; C:\ Program Files \ Python_3.6 \; C:\ ProgramData \ Oracle \ Java \ javapath; C:\ Program Files(x86)\ Common Files \ Intel \ Shared

请注意,Python 2.7是第一位,Python 3.5是第二位。

  • 因此,运行python命令将启动python 2.7(如果使用Python 3.5,则同一命令将启动Python 3.5)。
  • Running py -2启动Python 2.7(因为第二个Python是不兼容的Python 3.5 py -2)。运行py -3启动Python 3.5(因为它是Python 3.x)
  • 如果您稍后在路径中使用另一个python,则会像这样启动:py -4。如果/当发布Python版本4时,这可能会更改。

现在py -4py -5等在我的系统上输出:Requested Python version (4) not installedRequested Python version (5) not installed等。

希望这已经足够清楚了。

To install and run any version of Python in the same system follow my guide below.


For example say you want to install Python 2.x and Python 3.x on the same Windows system.

  1. Install both of their binary releases anywhere you want.

    • When prompted do not register their file extensions and
    • do not add them automatically to the PATH environment variable
  2. Running simply the command python the executable that is first met in PATH will be chosen for launch. In other words, add the Python directories manually. The one you add first will be selected when you type python. Consecutive python programs (increasing order that their directories are placed in PATH) will be chosen like so:

    • py -2 for the second python
    • py -3 for the third python etc..
  3. No matter the order of “pythons” you can:

    • run Python 2.x scripts using the command: py -2 (Python 3.x functionality) (ie. the first Python 2.x installation program found in your PATH will be selected)
    • run Python 3.x scripts using the command: or py -3 (ie. the first Python 3.x installation program found in your PATH will be selected)

In my example I have Python 2.7.14 installed first and Python 3.5.3. This is how my PATH variable starts with:

PATH=C:\Program Files\Microsoft MPI\Bin\;C:\Python27;C:\Program Files\Python_3.6\Scripts\;C:\Program Files\Python_3.6\;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Common Files\Intel\Shared

Note that Python 2.7 is first and Python 3.5 second.

  • So running python command will launch python 2.7 (if Python 3.5 the same command would launch Python 3.5).
  • Running py -2 launches Python 2.7 (because it happens that the second Python is Python 3.5 which is incompatible with py -2). Running py -3 launches Python 3.5 (because it’s Python 3.x)
  • If you had another python later in your path you would launch like so: py -4. This may change if/when Python version 4 is released.

Now py -4 or py -5 etc. on my system outputs: Requested Python version (4) not installed or Requested Python version (5) not installed etc.

Hopefully this is clear enough.


回答 5

从3.3版开始,Windows版具有Python启动器,请查看3.4节。适用于Windows的Python启动器

Starting version 3.3 Windows version has Python launcher, please take a look at section 3.4. Python Launcher for Windows


回答 6

您可以执行以下操作:

安装cmder。像使用cmd终端一样打开并使用Cmder。使用命令别名来创建命令别名。

我做了以下事情:

alias python2 = c:\python27\python.exe
alias python3 = c:\python34\python.exe

就是这样!;-)

Here’s what you can do:

Install cmder. Open and use Cmder as you would with you cmd terminal. Use the command alias to create command aliases.

I did the following:

alias python2 = c:\python27\python.exe
alias python3 = c:\python34\python.exe

And that’s it! ;-)


回答 7

我实际上只是想到了一个有趣的解决方案。尽管Windows不允许您轻松给程序加上别名,但是您可以创建重命名的批处理文件来调用当前程序。

不要重命名可执行文件,否则将破坏很多东西,包括pip,请在与python2.exe相同的目录中创建文件python2.bat。然后添加以下行:

%~dp0python %*

这个古老的语法是什么意思?好吧,这是一个批处理脚本(Windows版本的bash)。%〜dp0获取当前目录,%*会将所有传递给脚本的参数传递给python。

对python3.bat重复

您还可以对pip和其他实用程序执行相同的操作,只需将文件中的python单词替换为pip或任何文件名即可。别名将是文件的名称。

最好的是,Windows添加到PATH时会忽略扩展名,因此运行

python3

将启动python3版本,命令python2将启动python2版本。

顺便说一句,这与Spyder用于将自身添加到Windows上的路径的技术相同。:)

I actually just thought of an interesting solution. While Windows will not allow you to easily alias programs, you can instead create renamed batch files that will call the current program.

Instead of renaming the executable which will break a lot of thing including pip, create the file python2.bat in the same directory as the python2.exe. Then add the following line:

%~dp0python %*

What does this archaic syntax mean? Well, it’s a batch script, (Windows version of bash). %~dp0 gets the current directory and %* will just pass all the arguments to python that were passed to the script.

Repeat for python3.bat

You can also do the same for pip and other utilities, just replace the word python in the file with pip or whathever the filename. The alias will be whatever the file is named.

Best of all, when added to the PATH, Windows ignores the extension so running

python3

Will launch the python3 version and and the command python2 will launch the python2 version.

BTW, this is the same technique Spyder uses to add itself to the path on Windows. :)


回答 8

您可以在一台计算机上安装多个版本的Python,并且在安装过程中可以选择让其中一个与Python文件扩展名关联。如果安装模块,则将有不同版本的安装程序包,或者您可以选择要定位的版本。由于他们通常会将自己安装到解释器版本的site-packages目录中,因此不应有任何冲突(但我尚未对此进行测试)。要选择哪个版本的python,您必须手动指定解释器的路径(如果它不是默认路径)。据我所知,它们将共享相同的PATH和PYTHONPATH变量,这可能是一个问题。

注意:我运行Windows XP。我不知道其他版本是否会发生任何更改,但我看不出会有任何原因。

You can install multiple versions of Python one machine, and during setup, you can choose to have one of them associate itself with Python file extensions. If you install modules, there will be different setup packages for different versions, or you can choose which version you want to target. Since they generally install themselves into the site-packages directory of the interpreter version, there shouldn’t be any conflicts (but I haven’t tested this). To choose which version of python, you would have to manually specify the path to the interpreter if it is not the default one. As far as I know, they would share the same PATH and PYTHONPATH variables, which may be a problem.

Note: I run Windows XP. I have no idea if any of this changes for other versions, but I don’t see any reason that it would.


回答 9

我在装有Python 2.7和Python 3.4的Windows计算机上所做的工作是,在与Python.exe文件相同的目录中编写了一个简单的.bat文件。他们看起来像

cmd /k "c:\python27\python.exe" %*

%*允许您随后添加参数(Python文件)。我相信/ k在完成运行脚本后使提示保持打开状态。然后将其另存为python27.bat,然后转到Python 3目录并在其中创建一个bat文件。现在我可以在命令行中编写

Python27 helloworld.py

要么

Python34 helloworld.py

它们将在各自的Python版本中运行。确保C:\ python27C:\ python34在您的环境变量。

我从这里得到答案

What I have done on my own windows computer where I have Python 2.7 and Python 3.4 installed is I wrote a simple .bat file in the same directory as my Python.exe files. They look something like,

cmd /k "c:\python27\python.exe" %*

The %* allows you to add arguments (Python files) afterwards. I believe /k keeps the prompt open after it finishes running the script. Then I save that as python27.bat Then I go to my Python 3 directory and make a bat file there. Now in my command line I can write

Python27 helloworld.py

Or

Python34 helloworld.py

And they will run in their respective versions of Python. Make sure that c:\python27 and c:\python34 are in your environment variables.

I got my answer from here


回答 10

我按照此处的说明分三个步骤进行了操作:全部直接从此处获取:http : //ipython.readthedocs.io/en/stable/install/kernel_install.html。我目前在Windows 8上运行Python 2.x,并安装了Anaconda 4.2.13。

1)首先安装最新版本的python:

conda create -n python3 python=3 ipykernel

2)接下来激活python3

activate python3

3)安装内核:

python -m ipykernel install --user

如果您已经安装了Python 3并且想要安装2,请切换上面的2和3。当您打开一个新笔记本时,现在可以在Python 2或3之间进行选择。

I did this in three steps by following the instructions here: This is all taken directly from here: http://ipython.readthedocs.io/en/stable/install/kernel_install.html. I’m currently running Python 2.x on Windows 8 and have Anaconda 4.2.13 installed.

1) First install the latest version of python:

conda create -n python3 python=3 ipykernel

2) Next activate python3

activate python3

3) Install the kernel:

python -m ipykernel install --user

If you have Python 3 installed and want to install 2, switch the 2 and the 3 above. When you open a new notebook, you can now choose between Python 2 or 3.


回答 11

安装Python后检查系统环境变量,python 3的目录应该首先在PATH变量中,然后是python 2。

Windows使用的路径变量最先匹配。

和往常一样,在这种情况下py -2将启动python2。

Check your system environment variables after installing Python, python 3’s directories should be first in your PATH variable, then python 2.

Whichever path variable matches first is the one Windows uses.

As always py -2 will launch python2 in this scenario.


回答 12

我自己遇到了这个问题,我在.bat中制作了启动程序,因此您可以选择要启动的版本。

唯一的问题是您的.py必须位于python文件夹中,但是无论如何,这里是代码:

对于Python2

@echo off
title Python2 Launcher by KinDa
cls
echo Type the exact version of Python you use (eg. 23, 24, 25, 26)
set/p version=
cls
echo Type the file you want to launch without .py (eg. hello world, calculator)
set/p launch=
path = %PATH%;C:\Python%version%
cd C:\Python%version%
python %launch%.py
pause

对于Python3

@echo off
title Python3 Launcher by KinDa
cls
echo Type the exact version of Python you use (eg. 31, 32, 33, 34)
set/p version=
cls
echo Type the file you want to launch without .py (eg. hello world, calculator)
set/p launch=
cls
set path = %PATH%:C:\Python%version%
cd C:\Python%version%
python %launch%.py
pause

将它们另存为.bat并按照其中的说明进行操作。

I have encountered that problem myself and I made my launchers in a .bat so you could choose the version you want to launch.

The only problem is your .py must be in the python folder, but anyway here is the code:

For Python2

@echo off
title Python2 Launcher by KinDa
cls
echo Type the exact version of Python you use (eg. 23, 24, 25, 26)
set/p version=
cls
echo Type the file you want to launch without .py (eg. hello world, calculator)
set/p launch=
path = %PATH%;C:\Python%version%
cd C:\Python%version%
python %launch%.py
pause

For Python3

@echo off
title Python3 Launcher by KinDa
cls
echo Type the exact version of Python you use (eg. 31, 32, 33, 34)
set/p version=
cls
echo Type the file you want to launch without .py (eg. hello world, calculator)
set/p launch=
cls
set path = %PATH%:C:\Python%version%
cd C:\Python%version%
python %launch%.py
pause

Save them as .bat and follow the instructions inside.


回答 13

将最常用的一个(在本例中为3.3)安装在另一个的顶部。这将迫使IDLE使用您想要的那个。

或者(来自python3.3自述文件):

安装多个版本

在Unix和Mac系统上,如果要使用相同的安装前缀(配置脚本的–prefix参数)安装多个版本的Python,则必须注意,安装其他版本不会覆盖您的主要python可执行文件。使用“ make altinstall”安装的所有文件和目录都包含主要版本和次要版本,因此可以并行存在。“ make install”还会创建$ {prefix} / bin / python3,它引用了$ {prefix} /bin/pythonX.Y。如果打算使用相同的前缀安装多个版本,则必须确定哪个版本(如果有)是您的“主要”版本。使用“进行安装”安装该版本。使用“ make altinstall”安装所有其他版本。

例如,如果要安装Python 2.6、2.7和3.3,而2.7是主要版本,则可以在2.7构建目录中执行“ make install”,在其他构建目录中执行“ make altinstall”。

Install the one you use most (3.3 in my case) over the top of the other. That’ll force IDLE to use the one you want.

Alternatively (from the python3.3 README):

Installing multiple versions

On Unix and Mac systems if you intend to install multiple versions of Python using the same installation prefix (–prefix argument to the configure script) you must take care that your primary python executable is not overwritten by the installation of a different version. All files and directories installed using “make altinstall” contain the major and minor version and can thus live side-by-side. “make install” also creates ${prefix}/bin/python3 which refers to ${prefix}/bin/pythonX.Y. If you intend to install multiple versions using the same prefix you must decide which version (if any) is your “primary” version. Install that version using “make install”. Install all other versions using “make altinstall”.

For example, if you want to install Python 2.6, 2.7 and 3.3 with 2.7 being the primary version, you would execute “make install” in your 2.7 build directory and “make altinstall” in the others.


回答 14

我只需要安装它们。然后,我在http://defaultprogramseditor.com/的 “文件类型设置” /“上下文菜单” /搜索:“ py”下使用了免费的(可移植的)软件,选择了.py文件,并为该文件添加了“打开”命令2 IDLE,方法是复制名为“用IDLE打开”的现有命令,将名称更改为IDLE 3.4.1 / 2.7.8,并在程序路径中重新复制各个版本的文件号。现在,我只需右键单击.py文件,然后选择我要使用的IDLE。如果愿意,可以使用直接口译员做同样的事情。

I just had to install them. Then I used the free (and portable) soft at http://defaultprogramseditor.com/ under “File type settings”/”Context menu”/search:”py”, chose .py file and added an ‘open’ command for the 2 IDLE by copying the existant command named ‘open with IDLE, changing names to IDLE 3.4.1/2.7.8, and remplacing the files numbers of their respective versions in the program path. Now I have just to right click the .py file and chose which IDLE I want to use. Can do the same with direct interpreters if you prefer.


回答 15

仅当您在Python IDE中运行代码时才有效

我在Windows操作系统上同时安装了Python 2.7和Python 3.3。如果我尝试启动文件,通常会在python 2.7 IDE上打开它。解决此问题的方法是,当我选择在python 3.3上运行代码时,我打开python 3.3 IDLE(Python GUI),选择文件,使用IDLE打开文件并保存。然后,当我运行我的代码时,它将运行到当前打开它的IDLE。反之亦然。

Only Works if your running your code in your Python IDE

I have both Python 2.7 and Python 3.3 installed on my windows operating system. If I try to launch a file, it will usually open up on the python 2.7 IDE. How I solved this issue, was when I choose to run my code on python 3.3, I open up python 3.3 IDLE(Python GUI), select file, open my file with the IDLE and save it. Then when I run my code, it runs to the IDLE that I currently opened it with. It works vice versa with 2.7.


回答 16

我在Windows 10pro上同时安装了python 2.7.13和python 3.6.1,当我尝试使用pip2或pip3时,出现了同样的“致命错误”。

我所做的纠正操作是转到python.exe的python 2和python 3文件的位置,并为每个文件创建一个副本,然后根据其中的python版本,将每个副本重命名为python2.exe和python3.exe。安装文件夹。因此,我在每个python安装文件夹中都有python.exe文件和python2.exe或python3.exe(取决于python版本)。

当我键入pip2或pip3时,这解决了我的问题。

I have installed both python 2.7.13 and python 3.6.1 on windows 10pro and I was getting the same “Fatal error” when I tried pip2 or pip3.

What I did to correct this was to go to the location of python.exe for python 2 and python 3 files and create a copy of each, I then renamed each copy to python2.exe and python3.exe depending on the python version in the installation folder. I therefore had in each python installation folder both a python.exe file and a python2.exe or python3.exe depending on the python version.

This resolved my problem when I typed either pip2 or pip3.


回答 17

如果您无法使用其他任何功能,请打开所选版本的解释器(我更喜欢使用iPython),然后执行以下操作:

import subprocess

subprocess.call('python script.py -flags')

这将使用您当前正在使用的python版本。对于单个脚本来说效果很好,但是如果您运行的脚本很多,则会很快失去控制,在这种情况下,您始终可以在其中包含所有这些调用的情况下创建批处理文件。不是最优雅的答案,但它可以工作。

有没有一种方法可以为Linux中的不同python版本创建别名?

If you can’t get anything else to work, open an interpreter in whichever version you choose (I prefer using iPython) and:

import subprocess

subprocess.call('python script.py -flags')

This uses whichever python version you are currently operating under. Works fine for a single script, but will quickly get out of hand if there are lots of scripts you run, in which case you can always make a batch file with all of these calls inside. Not the most elegant answer, but it works.

Is there a way to make aliases for different python version a la Linux?


如何找出Python对象是否是字符串?

问题:如何找出Python对象是否是字符串?

如何检查Python对象是字符串(常规还是Unicode)?

How can I check if a Python object is a string (either regular or Unicode)?


回答 0

Python 2

使用isinstance(obj, basestring)一个对象来测试obj

文件

Python 2

Use isinstance(obj, basestring) for an object-to-test obj.

Docs.


回答 1

Python 2

要检查对象o是否是字符串类型的子类的字符串类型:

isinstance(o, basestring)

因为str和和unicode都是的子类basestring

检查的类型o是否完全是str

type(o) is str

检查是否o是的实例str或的任何子类str

isinstance(o, str)

以上还为Unicode字符串的工作,如果你更换str使用unicode

但是,您可能根本不需要进行显式类型检查。“鸭子打字”可能符合您的需求。请参阅http://docs.python.org/glossary.html#term-duck-typing

另请参阅在python中检查类型的规范方法是什么?

Python 2

To check if an object o is a string type of a subclass of a string type:

isinstance(o, basestring)

because both str and unicode are subclasses of basestring.

To check if the type of o is exactly str:

type(o) is str

To check if o is an instance of str or any subclass of str:

isinstance(o, str)

The above also work for Unicode strings if you replace str with unicode.

However, you may not need to do explicit type checking at all. “Duck typing” may fit your needs. See http://docs.python.org/glossary.html#term-duck-typing.

See also What’s the canonical way to check for type in python?


回答 2

Python 3

在Python 3.x basestring中,str唯一的字符串类型(具有Python 2.x的语义unicode)不再可用。

因此,Python 3.x中的检查只是:

isinstance(obj_to_test, str)

这是对官方转换工具的修复2to3:转换basestringstr

Python 3

In Python 3.x basestring is not available anymore, as str is the sole string type (with the semantics of Python 2.x’s unicode).

So the check in Python 3.x is just:

isinstance(obj_to_test, str)

This follows the fix of the official 2to3 conversion tool: converting basestring to str.


回答 3

Python 2和3

(兼容)

如果您不想检查Python版本(2.x与3.x),请使用sixPyPI)及其string_types属性:

import six

if isinstance(obj, six.string_types):
    print('obj is a string!')

six(一个重量很轻的单文件模块)中,它只是在做这件事

import sys
PY3 = sys.version_info[0] == 3

if PY3:
    string_types = str
else:
    string_types = basestring

Python 2 and 3

(cross-compatible)

If you want to check with no regard for Python version (2.x vs 3.x), use six (PyPI) and its string_types attribute:

import six

if isinstance(obj, six.string_types):
    print('obj is a string!')

Within six (a very light-weight single-file module), it’s simply doing this:

import sys
PY3 = sys.version_info[0] == 3

if PY3:
    string_types = str
else:
    string_types = basestring

回答 4

我发现了这个更多pythonic

if type(aObject) is str:
    #do your stuff here
    pass

由于类型对象是单例,因此可以用于将对象与str类型进行比较

I found this ans more pythonic:

if type(aObject) is str:
    #do your stuff here
    pass

since type objects are singleton, is can be used to do the compare the object to the str type


回答 5

如果一个人想从明确的类型检查(也有说走就走很好的理由远离它),可能是最安全的弦协议的一部分,以检查:

str(maybe_string) == maybe_string

它不会通过迭代的迭代或迭代器,它不会调用列表的串一个字符串,它正确地检测弦乐器的弦。

当然有缺点。例如,str(maybe_string)可能是繁重的计算。通常,答案取决于它

编辑:作为@Tcll 指出的意见,问题实际上询问的方式同时检测unicode字符串和字节串。在Python 2上,此答案将失败,但包含非ASCII字符的unicode字符串将exceptions,在Python 3上,它将False为所有字节串返回。

If one wants to stay away from explicit type-checking (and there are good reasons to stay away from it), probably the safest part of the string protocol to check is:

str(maybe_string) == maybe_string

It won’t iterate through an iterable or iterator, it won’t call a list-of-strings a string and it correctly detects a stringlike as a string.

Of course there are drawbacks. For example, str(maybe_string) may be a heavy calculation. As so often, the answer is it depends.

EDIT: As @Tcll points out in the comments, the question actually asks for a way to detect both unicode strings and bytestrings. On Python 2 this answer will fail with an exception for unicode strings that contain non-ASCII characters, and on Python 3 it will return False for all bytestrings.


回答 6

为了检查您的变量是否是某些东西,您可以像这样:

s='Hello World'
if isinstance(s,str):
#do something here,

isistance的输出将为您提供布尔值True或False,以便您可以进行相应的调整。您可以通过最初使用以下命令检查您的值的期望首字母缩写:type(s)这将返回您键入“ str”,以便您可以在isistance函数中使用它。

In order to check if your variable is something you could go like:

s='Hello World'
if isinstance(s,str):
#do something here,

The output of isistance will give you a boolean True or False value so you can adjust accordingly. You can check the expected acronym of your value by initially using: type(s) This will return you type ‘str’ so you can use it in the isistance function.


回答 7

我可能会像其他人提到的那样以鸭子打字的方式处理这个问题。我怎么知道一个字符串真的是一个字符串?好吧,显然是通过转换为字符串!

def myfunc(word):
    word = unicode(word)
    ...

如果arg已经是字符串或unicode类型,则real_word将保持其值不变。如果传递的对象实现一个__unicode__方法,则该方法用于获取其unicode表示形式。如果传递的对象不能用作字符串,则unicode内建函数引发异常。

I might deal with this in the duck-typing style, like others mention. How do I know a string is really a string? well, obviously by converting it to a string!

def myfunc(word):
    word = unicode(word)
    ...

If the arg is already a string or unicode type, real_word will hold its value unmodified. If the object passed implements a __unicode__ method, that is used to get its unicode representation. If the object passed cannot be used as a string, the unicode builtin raises an exception.


回答 8

isinstance(your_object, basestring)

如果您的对象确实是字符串类型,则将为True。’str’是保留字。

抱歉,正确的答案是使用’basestring’而不是’str’,以便它也包括unicode字符串-如上文其他响应者所述。

isinstance(your_object, basestring)

will be True if your object is indeed a string-type. ‘str’ is reserved word.

my apologies, the correct answer is using ‘basestring’ instead of ‘str’ in order of it to include unicode strings as well – as been noted above by one of the other responders.


回答 9

今天晚上,我遇到了一种情况,我以为我必须检查一下str类型,但事实证明我没有。

我解决问题的方法可能在许多情况下都可以使用,因此,在其他阅读此问题的人员感兴趣的情况下,我在下面提供了此方法(仅适用于Python 3)。

# NOTE: fields is an object that COULD be any number of things, including:
# - a single string-like object
# - a string-like object that needs to be converted to a sequence of 
# string-like objects at some separator, sep
# - a sequence of string-like objects
def getfields(*fields, sep=' ', validator=lambda f: True):
    '''Take a field sequence definition and yield from a validated
     field sequence. Accepts a string, a string with separators, 
     or a sequence of strings'''
    if fields:
        try:
            # single unpack in the case of a single argument
            fieldseq, = fields
            try:
                # convert to string sequence if string
                fieldseq = fieldseq.split(sep)
            except AttributeError:
                # not a string; assume other iterable
                pass
        except ValueError:
            # not a single argument and not a string
            fieldseq = fields
        invalid_fields = [field for field in fieldseq if not validator(field)]
        if invalid_fields:
            raise ValueError('One or more field names is invalid:\n'
                             '{!r}'.format(invalid_fields))
    else:
        raise ValueError('No fields were provided')
    try:
        yield from fieldseq
    except TypeError as e:
        raise ValueError('Single field argument must be a string'
                         'or an interable') from e

一些测试:

from . import getfields

def test_getfields_novalidation():
    result = ['a', 'b']
    assert list(getfields('a b')) == result
    assert list(getfields('a,b', sep=',')) == result
    assert list(getfields('a', 'b')) == result
    assert list(getfields(['a', 'b'])) == result

This evening I ran into a situation in which I thought I was going to have to check against the str type, but it turned out I did not.

My approach to solving the problem will probably work in many situations, so I offer it below in case others reading this question are interested (Python 3 only).

# NOTE: fields is an object that COULD be any number of things, including:
# - a single string-like object
# - a string-like object that needs to be converted to a sequence of 
# string-like objects at some separator, sep
# - a sequence of string-like objects
def getfields(*fields, sep=' ', validator=lambda f: True):
    '''Take a field sequence definition and yield from a validated
     field sequence. Accepts a string, a string with separators, 
     or a sequence of strings'''
    if fields:
        try:
            # single unpack in the case of a single argument
            fieldseq, = fields
            try:
                # convert to string sequence if string
                fieldseq = fieldseq.split(sep)
            except AttributeError:
                # not a string; assume other iterable
                pass
        except ValueError:
            # not a single argument and not a string
            fieldseq = fields
        invalid_fields = [field for field in fieldseq if not validator(field)]
        if invalid_fields:
            raise ValueError('One or more field names is invalid:\n'
                             '{!r}'.format(invalid_fields))
    else:
        raise ValueError('No fields were provided')
    try:
        yield from fieldseq
    except TypeError as e:
        raise ValueError('Single field argument must be a string'
                         'or an interable') from e

Some tests:

from . import getfields

def test_getfields_novalidation():
    result = ['a', 'b']
    assert list(getfields('a b')) == result
    assert list(getfields('a,b', sep=',')) == result
    assert list(getfields('a', 'b')) == result
    assert list(getfields(['a', 'b'])) == result

回答 10

它很简单,请使用以下代码(我们假设提到的对象为obj)-

if type(obj) == str:
    print('It is a string')
else:
    print('It is not a string.')

Its simple, use the following code (we assume the object mentioned to be obj)-

if type(obj) == str:
    print('It is a string')
else:
    print('It is not a string.')

回答 11

您可以通过连接一个空字符串来测试它:

def is_string(s):
  try:
    s += ''
  except:
    return False
  return True

编辑

在指出指出列表失败的评论后纠正我的答案

def is_string(s):
  return isinstance(s, basestring)

You can test it by concatenating with an empty string:

def is_string(s):
  try:
    s += ''
  except:
    return False
  return True

Edit:

Correcting my answer after comments pointing out that this fails with lists

def is_string(s):
  return isinstance(s, basestring)

回答 12

对于类似字符串的鸭式打字方法,它具有同时使用Python 2.x和3.x的优点:

def is_string(obj):
    try:
        obj + ''
        return True
    except TypeError:
        return False

明智的鱼转而使用鸭式输入法之前就与鸭式输入isinstance方式很接近,只是+=对列表的含义与以前不同+

For a nice duck-typing approach for string-likes that has the bonus of working with both Python 2.x and 3.x:

def is_string(obj):
    try:
        obj + ''
        return True
    except TypeError:
        return False

wisefish was close with the duck-typing before he switched to the isinstance approach, except that += has a different meaning for lists than + does.


回答 13

if type(varA) == str or type(varB) == str:
    print 'string involved'

来自EDX-在线类MITx:6.00.1x使用Python进行计算机科学和编程简介

if type(varA) == str or type(varB) == str:
    print 'string involved'

from EDX – online course MITx: 6.00.1x Introduction to Computer Science and Programming Using Python