【问题标题】:Unknown Code Error involving Python float(sys.argv[1])涉及 Python float(sys.argv[1]) 的未知代码错误
【发布时间】:2014-03-13 03:33:31
【问题描述】:

我正在使用 Python 3 开发 Farenheiht-Celsius 转换器。我收到了一些不起作用的示例代码,但我不知道为什么。这是我的代码:

#!home/andres/Documents/Executables
import sys
f = int(sys.argv[1])
print (f, "degrees farenheit is equal to", )
print (5.0/9*(f - 32), "degrees Celsius.")

当然,我得到如下语法错误:

Traceback (most recent call last):
  File "/home/andres/Documents/Executables/f2c.py", line 3, in <module>
    f = int(sys.argv[1])
IndexError: list index out of range
>>> 

注意事项:

  1. 我对 sys.argv 命令有一个(粗略的)理解,该命令与命令行参数一起使用。

  2. 我的老师打算让我调整这个代码。

    $ ./f2c.py 212
    212.0 华氏度等于 100.0 摄氏度。

(是的,我知道上面的部分没有显示为代码,但我不知道如何修复它。) 3. 我正在运行 Ubuntu,但仍然习惯它。原谅我的无知。

想想就是这样。谢谢!

编辑:这是我的 shell 会话,可能会有所帮助:

andres@Beta:~/Documents/Executables$ ./f2c.py
bash: ./f2c.py: /bin/env: bad interpreter: No such file or directory
andres@Beta:~/Documents/Executables$ chmod +x f2c.py
andres@Beta:~/Documents/Executables$ ./f2c.py 12
bash: ./f2c.py: /bin/env: bad interpreter: No such file or directory
andres@Beta:~/Documents/Executables$

【问题讨论】:

  • 在交互式解释器中使用sys.argv 没有多大/任何意义。只有按照说明运行脚本才有意义,因为sys.argv 包含来自 shell 的命令行指令。
  • 你的 shebang #!home/andres/Documents/Executables 没有多大意义。

标签: python ubuntu python-3.x arguments sys


【解决方案1】:

我相信您正在解释器中运行代码,使用 IDE 或 python 提示符。这将不起作用,因为 sys.argv 依赖于从终端命令行调用程序。 当我这样做时,您的代码可以正常工作,

[myself@localhost ~]$ python f2c.py 12
12 degrees farenheit is equal to -11.1111111111 degrees Celsius.

要将其作为 ./f2c.py 运行,您需要做两件事,

编辑您的代码以类似于以下内容

#!/usr/bin/env python

import sys
f = int(sys.argv[1])
print (f, "degrees farenheit is equal to", )
print (5.0/9*(f - 32), "degrees Celsius.")

这是一个命令 linux shell 例如 bash 调用 'env' 程序并告诉它我们需要使用 python 来运行它

其次,我们需要使文件可执行,这样做是为了

chmod +x f2c.py

现在可以如下调用

[myself@localhost ~]$ ./f2c.py 12
12 degrees farenheit is equal to -11.1111111111 degrees Celsius.

顺便说一句,正确的拼写是华氏。

【讨论】:

  • 请注意,在 Windows 上,您已经可以将其作为 ./f2c.py 运行而无需任何这些步骤(假设您让 Python 安装程序安装启动器并正确连接它,我认为这是默认设置)至少在来自 python.org 的 CPython 3.3 和 3.4 中)。我意识到 OP 正在使用 Ubuntu,我只是想在这里发表评论,以防有同样问题的任何 Windows 用户来到这里并想知道为什么 chmod 给他们错误以及为什么 shebang 没有效果等等......跨度>
  • andres@Beta:~/Documents/Executables$ ./f2c.py bash: ./f2c.py: /bin/env: 错误的解释器:没有这样的文件或目录 andres@Beta:~/ Documents/Executables$ chmod +x f2c.py andres@Beta:~/Documents/Executables$ ./f2c.py 12 bash: ./f2c.py: /bin/env: 错误的解释器:没有这样的文件或目录 andres@Beta :~/Documents/Executables$
  • @Qu0rk 不确定这是怎么发生的。我认为问题可能是你如何运行python。 'which python' 命令会为您显示什么?你是如何安装和运行python的?你是从windows复制文件吗?这也会搞砸 #!/bin/env python 。我将整个脚本粘贴到我的答案中以进行澄清
  • 使用 sudo apt-get install python3-minimal 安装了 python 我还从 Ubuntu 商店安装了 Python IDLE。我从我正在学习的书的 .pdf 中复制了这个文件。感谢您的帮助。
  • 不应该是/usr/bin/env吗?我没有运行 Ubuntu,但它在 Debian 和 OS X 上是 /usr/bin/env...
猜你喜欢
  • 1970-01-01
  • 2011-01-03
  • 1970-01-01
  • 2017-10-25
  • 1970-01-01
  • 2010-10-17
  • 1970-01-01
  • 2016-08-07
相关资源
最近更新 更多