【问题标题】:Python name error in LInux terminal when the input is defined定义输入时,LINux 终端中的 Python 名称错误
【发布时间】:2021-04-06 19:23:52
【问题描述】:

我在 Linux 上运行 python 3.6。当我使用 python shell 测试代码时,它按预期工作。但是,如果从 linux 终端运行,则会出现名称错误。

#!/usr/bin/python
print("Hi")
name = input("What\'s your name?")
print (name, "is a cool name")

然后从linux终端输入名字后,我得到以下错误:

Traceback (most recent call last):
  File "./test.py", line 3, in <module>
    name = input("What\'s your name?")
  File "<string>", line 1, in <module>
NameError: name 'Matt' is not defined

我知道如果在 python 2 上运行,你需要使用原始输入,但是这在 python 3 中没有使用。是否有另一行代码让 linux 终端接受它,比如#!/usr

【问题讨论】:

  • 你是如何运行它的?
  • /usr/bin/python --version 带给你什么?
  • 试试:print '{} is a cool name'.format(name)
  • 不,我的意思是如果你在终端中输入/usr/bin/python --version 会发生什么。看起来你正在运行 python2,即使你不打算这样做。
  • @matt-333:发生的情况是您同时安装了 python2 和 python3。我的猜测是 python3 是路径中的第一个,所以当你运行 $ python 时,你正在运行 python3,但 /usr/bin/python 实际上是 python2。您可以使用$ which python$ type python 查看它的位置。

标签: python linux input


【解决方案1】:

使用 shebang#!/usr/bin/python 您是在告诉系统使用 Python 2。

在 Python 2 中,您需要将 input 更改为 raw_input,如下所示:

#!/usr/bin/python
print("Hi")
name = raw_input("What\'s your name?")
print(name, "is a cool name")

更多信息请参见Greeting program

但是,要告诉系统使用 Python 3 运行脚本,请将您的 shebang 行更改为 #!/usr/bin/python3,或者最好是 #!/usr/bin/env python3

【讨论】:

  • 他说他使用的是 Python 3,不需要raw_input
  • @Barmar 对不起,我错过了那部分。我会更新我的答案。
【解决方案2】:

你可以这样运行:python3 test.py

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-13
    • 1970-01-01
    相关资源
    最近更新 更多