【问题标题】:hello world python program two version python on same machine你好世界python程序在同一台机器上的两个版本python
【发布时间】:2019-08-26 10:21:32
【问题描述】:

我在同一台 Windows 10 笔记本电脑上安装了 python2.7 和 python3.7.3。 现在我正在尝试单独运行程序。 在 windows cmd 我输入

cmd>py -2 print 'hello world'
C:\Users\data\installation\python2.7\python.exe: can't open file 'print': [Errno 2] No such file or directory

我尝试在 powershell 上运行

PS> python2  print 'hello world'
python2 : The term 'python2' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again.
At line:1 char:1
+ python2  print 'hello world'
+ ~~~~~~~
    + CategoryInfo          : ObjectNotFound: (python2:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException`

我尝试在 powershell 上运行

> py2 print 'hello world'
py2 : The term 'py2' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included,

验证路径是否正确,然后重试。 在行:1 字符:1 + py2 打印'你好世界' + ~~~ + CategoryInfo : ObjectNotFound: (py2:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException`

如果我只在 powershell 上运行

> py -2 print "hello world'

我得到以下提示 >>> 但没有别的

同样是问题

> py -3 print ('Hello World')
C:\Users\data\installation\python\python.exe: can't open file 'print': [Errno 2] No such file or directory`

我的脚本文件 (script.py) 是:

#! py -3
python --version

我读到了这些问题:

我希望 hello world 被打印出来,而不是出现这个错误。

【问题讨论】:

  • 当您使用 Windows 时,请检查您在系统环境中是否有到您的 python 的路径。此外,当您使用不同的 python 版本时,最好有 virtualenvs 并使用它们管理可运行的脚本。
  • 如何拥有 virtualenvs 请给一些链接

标签: python windows


【解决方案1】:

您没有正确使用启动器或命令。

py launcher for WindowsPython command-line binary itself 一样,不直接采用 Python 代码。所以你的第一行

py -2 print 'hello world'

不起作用,因为您要求 Python 可执行文件查找名为 print 的文件以作为 Python 脚本运行。您可以改为使用-c command line switch 来运行一行 Python 代码:

py -2 -c "print 'hello world'"

这告诉 Windows 控制台启动进程py,分别传入参数-2-cprint 'hello world'(最后一部分周围的" 使控制台无法将空格视为分隔符)。 py 启动器然后找到 Python 2.7 二进制文件,并使用剩余的参数运行它。

切换到 Powershell 尝试,第一个不起作用,因为 Windows 不知道在哪里可以找到 python2 exectable:

术语“python2”未被识别为 cmdlet、函数、脚本文件或可运行程序的名称

没有py2 可执行文件也没有

坚持使用py 启动器,作为您链接到建议的两个问题:

py -2 -c "print 'hello world'"

您的script.py 文件无法运行,因为第一行#! py -3 之后的所有内容都是Python 代码python --version 不是有效的 Python。这将起作用:

#! py -3
import sys
print(sys.version_info)

【讨论】: