标签归档:backwards-compatibility

Python的字符串格式化的许多方式-较旧的(即将被淘汰)吗?

问题:Python的字符串格式化的许多方式-较旧的(即将被淘汰)吗?

Python至少有六种格式化字符串的方式:

In [1]: world = "Earth"

# method 1a
In [2]: "Hello, %s" % world
Out[2]: 'Hello, Earth'

# method 1b
In [3]: "Hello, %(planet)s" % {"planet": world}
Out[3]: 'Hello, Earth'

# method 2a
In [4]: "Hello, {0}".format(world)
Out[4]: 'Hello, Earth'

# method 2b
In [5]: "Hello, {planet}".format(planet=world)
Out[5]: 'Hello, Earth'

# method 2c
In [6]: f"Hello, {world}"
Out[6]: 'Hello, Earth'

In [7]: from string import Template

# method 3
In [8]: Template("Hello, $planet").substitute(planet=world)
Out[8]: 'Hello, Earth'

不同方法的简要历史:

  • printf自从Python诞生以来,样式样式格式化就已经存在
  • Template班是在Python 2.4中引入
  • format方法在Python 2.6中引入
  • f-strings是在Python 3.6中引入的

我的问题是:

  • 是否printf不赞成使用-style格式?
  • 在中Template class,该substitute方法是否已弃用或将要弃用?(我不是在谈论safe_substitute,据我所知它提供了独特的功能)

类似的问题以及为什么我认为它们不是重复的:

也可以看看

Python has at least six ways of formatting a string:

In [1]: world = "Earth"

# method 1a
In [2]: "Hello, %s" % world
Out[2]: 'Hello, Earth'

# method 1b
In [3]: "Hello, %(planet)s" % {"planet": world}
Out[3]: 'Hello, Earth'

# method 2a
In [4]: "Hello, {0}".format(world)
Out[4]: 'Hello, Earth'

# method 2b
In [5]: "Hello, {planet}".format(planet=world)
Out[5]: 'Hello, Earth'

# method 2c
In [6]: f"Hello, {world}"
Out[6]: 'Hello, Earth'

In [7]: from string import Template

# method 3
In [8]: Template("Hello, $planet").substitute(planet=world)
Out[8]: 'Hello, Earth'

A brief history of the different methods:

  • printf-style formatting has been around since Pythons infancy
  • The Template class was introduced in Python 2.4
  • The format method was introduced in Python 2.6
  • f-strings were introduced in Python 3.6

My questions are:

  • Is printf-style formatting deprecated or going to be deprecated?
  • In the Template class, is the substitute method deprecated or going to be deprecated? (I’m not talking about safe_substitute, which as I understand it offers unique capabilities)

Similar questions and why I think they’re not duplicates:

  • Python string formatting: % vs. .format — treats only methods 1 and 2, and asks which one is better; my question is explicitly about deprecation in the light of the Zen of Python

  • String formatting options: pros and cons — treats only methods 1a and 1b in the question, 1 and 2 in the answer, and also nothing about deprecation

  • advanced string formatting vs template strings — mostly about methods 1 and 3, and doesn’t address deprecation

  • String formatting expressions (Python) — answer mentions that the original ‘%’ approach is planned to be deprecated. But what’s the difference between planned to be deprecated, pending deprecation and actual deprecation? And the printf-style method doesn’t raise even a PendingDeprecationWarning, so is this really going to be deprecated? This post is also quite old, so the information may be outdated.

See also


回答 0

尽管在文档中有各种各样的迹象表明,.formatf字符串优于%字符串,但尚无可行的方案来弃用后者。

在提交的问题#14123中:明确提及旧样式%字符串格式有一些警告,但不会很快消失。,受问题启发,表明目前没有计划弃用printf样式格式,有关%-formatting 的文档已被编辑为包含以下短语:

由于新的字符串格式语法更加灵活并且可以自然地处理元组和字典,因此建议将其用于新代码。但是,目前没有废弃过printf样式格式的计划

(强调我的。)

此短语稍后在commit Close#4966中删除:修改序列文档,以更好地解释现代Python的状态。这看起来似乎是一个迹象,表明不再支持%格式化的计划已经重新出现在卡上了……但是,深入研究Bug跟踪程序后,发现其意图恰恰相反。在错误跟踪器上,提交的作者描述了更改的特征,如下所示

  • 更改了描述printf样式格式与str.format方法之间关系的散文(故意消除了前者可能会消失的真正危险的暗示-认真考虑将其销毁是不切实际的)

换句话说,我们对%-formatting文档进行了两次连续更改,旨在明确强调不会被弃用,更不用说删除了。这些文档仍然对不同类型的字符串格式的相对优点持保留意见,但他们也清楚%格式不会被弃用或删除。

更重要的是,该段落的最新更改是在2017年3月,对此进行了更改…

此处描述的格式化操作表现出各种古怪,这些古怪会导致许多常见错误(例如无法正确显示元组和字典)。使用较新的格式化字符串文字或str.format接口有助于避免这些错误。这些替代方法还提供了更强大,灵活和可扩展的文本格式设置方法。

…对此:

此处描述的格式化操作表现出各种古怪,这些古怪会导致许多常见错误(例如无法正确显示元组和字典)。使用更新的格式化字符串文字,str.format接口或模板字符串可能有助于避免这些错误。这些选择中的每一个都提供了自己的权衡,并带来了简单性,灵活性和/或可扩展性的好处。

请注意,从“避免使用帮助”到“可以避免使用”的变化,以及关于.formatf和弦的清晰建议如何被蓬松,模棱两可的散文所取代,有关每种样式如何“提供自己的取舍和好处”。也就是说,不仅不再正式弃用卡片,而且当前的文档公开承认%格式至少比其他方法具有一些“好处”。

从这一切中我可以推断出,弃用或删除%格式的运动不仅步履蹒跚,而且被彻底永久地击败。

While there are various indications in the docs that .format and f-strings are superior to % strings, there’s no surviving plan to ever deprecate the latter.

In commit Issue #14123: Explicitly mention that old style % string formatting has caveats but is not going away any time soon., inspired by issue Indicate that there are no current plans to deprecate printf-style formatting, the docs on %-formatting were edited to contain this phrase:

As the new string-formatting syntax is more flexible and handles tuples and dictionaries naturally, it is recommended for new code. However, there are no current plans to deprecate printf-style formatting.

(Emphasis mine.)

This phrase was removed later, in commit Close #4966: revamp the sequence docs in order to better explain the state of modern Python. This might seem like a sign that a plan to deprecate % formatting was back on the cards… but diving into the bug tracker reveals that the intent was the opposite. On the bug tracker, the author of the commit characterises the change like this:

  • changed the prose that describes the relationship between printf-style formatting and the str.format method (deliberately removing the implication that the former is any real danger of disappearing – it’s simply not practical for us to seriously contemplate killing it off)

In other words, we’ve had two consecutive changes to the %-formatting docs intended to explicitly emphasise that it will not be deprecated, let alone removed. The docs remain opinionated on the relative merits of different kinds of string formatting, but they’re also clear the %-formatting isn’t going to get deprecated or removed.

What’s more, the most recent change to that paragraph, in March 2017, changed it from this…

The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer formatted string literals or the str.format interface helps avoid these errors. These alternatives also provide more powerful, flexible and extensible approaches to formatting text.

… to this:

The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer formatted string literals, the str.format interface, or template strings may help avoid these errors. Each of these alternatives provides their own trade-offs and benefits of simplicity, flexibility, and/or extensibility.

Notice the change from “helps avoid” to “may help avoid”, and how the clear recommendation of .format and f-strings has been replaced by fluffy, equivocal prose about how each style “provides their own trade-offs and benefits”. That is, not only is a formal deprecation no longer on the cards, but the current docs are openly acknowledging that % formatting at least has some “benefits” over the other approaches.

I’d infer from all this that the movement to deprecate or remove % formatting has not only faltered, but been defeated thoroughly and permanently.


回答 1

.format()方法旨在替换旧的%格式语法。后者已经不再强调,(但没有正式弃用尚未)。方法文档指出:

字符串格式化的这种方法是在Python 3的新标准,并应首选%格式化中所描述的字符串的格式化操作在新的代码。

(强调我的)。

为了保持向后兼容性,并让您更容易过渡,旧格式已经被留在原地现在。根据最初的PEP 3101提案

向后兼容

可以通过保留现有机制来保持向后兼容性。新系统不会与现有字符串格式化技术的任何方法名称发生冲突,因此这两个系统可以共存,直到需要弃用旧系统为止。

请注意,直到该淘汰旧系统为止;它尚未被弃用,但是只要您编写新代码,就将使用新系统

新系统的一个优点是您可以结合使用旧%格式化程序的元组和字典方法:

"{greeting}, {0}".format(world, greeting='Hello')

并可以通过 object.__format__()用于处理各个值格式钩子进行。

请注意,旧系统具有%Template类,后者允许您创建添加或更改其行为的子类。新型系统具有Formatter一流填充相同细分市场。

Python 3进一步远离了弃用,而是在printf-style String Formatting部分中给您警告:

注意:此处描述的格式化操作表现出各种古怪,导致许多常见错误(例如未能正确显示元组和字典)。使用较新的格式化字符串文字str.format()接口有助于避免这些错误。这些替代方法还提供了更强大,灵活和可扩展的文本格式设置方法。

Python 3.6还添加了格式化的字符串文字,将表达式内联格式字符串中。这些是使用内插值创建字符串的最快方法,应使用它,而不是str.format()在可以使用文字的任何地方。

The new .format() method is meant to replace the old % formatting syntax. The latter has been de-emphasised, (but not officially deprecated yet). The method documentation states as much:

This method of string formatting is the new standard in Python 3, and should be preferred to the % formatting described in String Formatting Operations in new code.

(Emphasis mine).

To maintain backwards compatibility and to make transition easier, the old format has been left in place for now. From the original PEP 3101 proposal:

Backwards Compatibility

Backwards compatibility can be maintained by leaving the existing mechanisms in place. The new system does not collide with any of the method names of the existing string formatting techniques, so both systems can co-exist until it comes time to deprecate the older system.

Note the until it comes time to deprecate the older system; it hasn’t been deprecated, but the new system is to be used whenever you write new code.

The new system has as an advantage that you can combine the tuple and dictionary approach of the old % formatter:

"{greeting}, {0}".format(world, greeting='Hello')

and is extensible through the object.__format__() hook used to handle formatting of individual values.

Note that the old system had % and the Template class, where the latter allows you to create subclasses that add or alter its behaviour. The new-style system has the Formatter class to fill the same niche.

Python 3 has further stepped away from deprecation, instead giving you warning in the printf-style String Formatting section:

Note: The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer formatted string literals or the str.format() interface helps avoid these errors. These alternatives also provide more powerful, flexible and extensible approaches to formatting text.

Python 3.6 also added formatted string literals, which in-line the expressions into the format strings. These are the fastest method of creating strings with interpolated values, and should be used instead of str.format() wherever you can use a literal.


回答 2

%尽管有其他答案,但不建议使用字符串格式的运算符,并且不会删除该运算符。
每次在Python开发列表中提出该主题时,都会有一个关于哪个更好的参数,但是对于是否要删除经典方法却没有争议-它会一直存在。尽管在PEP 3101上有说明,但Python 3.1来了又去了,%格式化仍然存在。

保持经典风格的说法很明确:它很简单,很快,可以快速完成简短的事情。使用该.format方法并不总是那么容易理解-几乎没有人-即使在核心开发人员中,也可以使用所提供的完整语法,.format而无需查看参考资料甚至在2009年,就有这样的消息:http:// mail。 python.org/pipermail/python-dev/2009-October/092529.html 几乎没有出现该主题。

2016年更新

在当前的Python开发版本(将成为Python 3.6)中,有第三种字符串内插方法,如PEP-0498所述。它定义了一个新的报价前缀f""(除了当前的u""b""r"")。

给字符串加上前缀f将在运行时在字符串对象上调用一个方法,该方法将自动将当前作用域中的变量插入到字符串中:

>>> value = 80
>>> f'The value is {value}.'
'The value is 80.'

The % operator for string formatting is not deprecated, and is not going to be removed – despite the other answers.
Every time the subject is raised on Python development list, there is strong controversy on which is better, but no controversy on whether to remove the classic way – it will stay. Despite being denoted on PEP 3101, Python 3.1 had come and gone, and % formatting is still around.

The statements for the keeping classic style are clear: it is simple, it is fast, it is quick to do for short things. Using the .format method is not always more readable – and barely anyone – even among the core developers, can use the full syntax provided by .format without having to look at the reference Even back in 2009, one had messages like this: http://mail.python.org/pipermail/python-dev/2009-October/092529.html – the subject had barely showed up in the lists since.

2016 update

In current Python development version (which will become Python 3.6) there is a third method of string interpolation, described on PEP-0498. It defines a new quote prefix f"" (besides the current u"", b"" and r"").

Prefixing a string by f will call a method on the string object at runtime, which will automatically interpolate variables from the current scope into the string:

>>> value = 80
>>> f'The value is {value}.'
'The value is 80.'

回答 3

圭多对此的最新立场似乎在这里指出:

Python 3.0的新增功能

PEP 3101:字符串格式化的新方法

用于内置字符串格式化操作的新系统取代了%字符串格式化运算符。(但是,仍然支持%运算符;它将在Python 3.1中弃用,并在以后的某个时间从语言中删除。)有关完整说明,请阅读PEP 3101。

PEP3101本身,它有最后的修改可以追溯到(周五,2011年9月30日),这样的晚的,一个没有进步,我想。

Guido’s latest position on this seems to be indicated here:

What’s New In Python 3.0

PEP 3101: A New Approach To String Formatting

A new system for built-in string formatting operations replaces the % string formatting operator. (However, the % operator is still supported; it will be deprecated in Python 3.1 and removed from the language at some later time.) Read PEP 3101 for the full scoop.

And the PEP3101 itself, which has the last modified dating back to (Fri, 30 Sep 2011), so no progress as of late on that one, I suppose.


回答 4

在查看较旧的Python文档和PEP 3101时,有一条语句表示将来将不推荐使用%运算符并将其从该语言中删除。在下面的语句是在Python文档的Python 3.0,3.1和3.2:

由于str.format()很新,因此许多Python代码仍然使用%运算符。但是,由于最终会从该语言中删除这种旧的格式设置样式,因此通常应使用str.format()。

如果转到Python 3.3和3.4文档中的同一部分,您将看到该语句已被删除。我也无法在文档中的任何其他地方找到任何其他声明,表明该运算符将不推荐使用或从该语言中删除。还需要注意的是,PEP3101两年半没有进行过修改(2011年9月30日,星期五)。

更新资料

PEP461接受将%格式添加到字节和字节数组中,并且应该是Python 3.5或3.6的一部分。这是%运算符还活着而且在踢的另一个迹象。

Looking at the older Python docs and PEP 3101 there was a statement that the % operator will be deprecated and removed from the language in the future. The following statement was in the Python docs for Python 3.0, 3.1, and 3.2:

Since str.format() is quite new, a lot of Python code still uses the % operator. However, because this old style of formatting will eventually be removed from the language, str.format() should generally be used.

If you go to the same section in Python 3.3 and 3.4 docs, you will see that statement has been removed. I also cannot find any other statement anywhere else in the documentation indicating that the operator will be deprecated or removed from the language. It’s also important to note that PEP3101 has not been modified in over two and a half years (Fri, 30 Sep 2011).

Update

PEP461 Adding % formatting to bytes and bytearray is accepted and should be part of Python 3.5 or 3.6. It’s another sign that the % operator is alive and kicking.


如何在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?