涉及Python float的未知代码错误(sys.argv [1])

时间:2014-02-13 23:46:12

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

我正在使用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度farehheit等于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$
    

1 个答案:

答案 0 :(得分:3)

我相信您正在使用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.
顺便说一下,正确的拼写是华氏度。

相关问题