【问题标题】:My mac terminal can't run python functions我的 mac 终端无法运行 python 函数
【发布时间】:2016-12-01 00:28:56
【问题描述】:

我尝试在 mac 终端上运行多个 python 函数,对于这个程序,它们都返回语法错误

def spam():
   print "R"

spam()

它返回了错误:

./test.py: line 1: syntax error near unexpected token `('
./test.py: line 1: `def spam():'

这确实是我能找到的最简单的功能。

需要明确的是,终端正在运行程序的其余部分,但它不能处理函数。

#!/usr/bin/python
import math

number = int(raw_input("What's your surd?"))

print type(number)

#Just to let us know what the input is

if type(number) == int:
    print "Number is an integer"
else:
    print "Please enter a number"

value = math.sqrt(number)

#Takes the number and square roots it

new_value =  int(value)

#Turns square root of number into an integer

if type(new_value) == int:
    print "Surd can be simplified"
    print new_value
else:
    print "Surd cannot be simplified"
    print value

这个程序运行良好,即使它现在有点错误,但下面的程序返回与前一个函数相同的错误。

# define a function
def print_factors(x):
   print("The factors of",x,"are:")
   for i in range(1, x + 1):
       if x % i == 0:
           print(i)


num = int(input("What's your number? "))

print_factors(num)

为什么终端在没有语法错误的情况下返回语法错误?

【问题讨论】:

  • 你是如何运行你的python程序的?试试python ./test.py
  • 您收到的错误消息表明bash shell 正在尝试解释该文件。如果您在 shell 中键入 def spam():,您将收到相同的消息。这意味着该文件不包含正确的 shebang 行(如您在较长摘录中显示的 #!/usr/bin/python)。

标签: python macos function terminal


【解决方案1】:

这里的问题(至少对于第一个示例)是您没有使用 python 解释器。终端正在为您的 python 代码使用 bash 解释器并且变得非常困惑。使用这样的命令来执行您的代码 python spam.py 。或者先运行python进入python命令解释器,然后在命令行解释器中输入你的代码。

开始时可能更容易的是获得像 PyCharm (https://www.jetbrains.com/pycharm/) 这样的 IDE,并通过他们的几个教程来感受它。

【讨论】:

    【解决方案2】:

    您的问题是您的 shell 不知道您正在运行 Python 脚本。您需要明确说明您应该使用 Python 解释器。您可以通过以下方式执行此操作:

    1) 在您的终端拨打python test.py

    2) 在 Python 脚本的顶部添加 #!/usr/bin/python(您可能需要更改系统上 Python 可执行文件的路径)。使脚本可执行,并在终端调用./test.py

    2) 的好处是您知道将使用哪个版本的 Python 来运行脚本(在您的情况下是 Python 2.x?)。

    方法 1) 将使用您的 PATH 中首先遇到的任何 Python 版本,可能是 Python 3 或 Python 2,具体取决于您是否在某个时候安装了 Python 3。您编写的代码适用于 Python 2.7,但不适用于 Python 3.x。当然你可以随时显式调用python2.7 ./test.py

    【讨论】:

      猜你喜欢
      • 2014-01-24
      • 1970-01-01
      • 2011-08-18
      • 2014-04-02
      • 1970-01-01
      • 2016-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多