【问题标题】:Code works in IDE but doesn't work in Terminal Console代码在 IDE 中有效,但在终端控制台中无效
【发布时间】:2019-05-21 14:42:36
【问题描述】:

我的代码在 Pycharm 中运行良好,但如果我在控制台(Ubuntu 终端)中键入 add,则会出现错误。

我在 Pycharm IDE 之外的控制台中遇到的错误:

Traceback (most recent call last):
  File "main.py", line 37, in <module>
    getStr = input('>: ')
  File "<string>", line 1, in <module>
NameError: name 'add' is not defined

我的代码:

#!/user/bin/python3
class Item:

    itemsCount = 0

    def __init__(self, sku, bWidth, bHeight, bLength, quantity, bWeight):

        self.sku = sku
        self.bWidth = bWidth
        self.bHeight = bHeight
        self.bLength = bLength
        self.quantity = quantity
        self.bWeight = bWeight
        Item.itemsCount += 1

    def DisplayItem(self):
        print('[SKU : ', self.sku, '] [Width : ', self.bWidth, '] [Height : ', self.bHeight,
              '] [bLength : ', self.bLength, '] [Quantity : ', self.quantity, '] [bWeight : ',
              self.bWeight, ']')


items = [Item]


print('Dan\'s Warehouse Inventory')
print('Current Stock in inventory : [', Item.itemsCount,']\n' )


while True:

    getStr = input('>: ')

    if getStr == 'add':
        getSku = input('SKU : ')
        getWidth = int(input('Width : '))
        getHeight = int(input('Height : '))
        getLength = int(input('bLength : '))
        getQuantity = int(input('Quantity : '))
        getWeight = int(input('Weight : '))

        items.append(Item(getSku, getWidth, getHeight, getLength, getQuantity, getWeight))
        print(Item.itemsCount)

    else:
        print('Invalid command.')

我不确定我做错了什么...感谢任何帮助!

【问题讨论】:

  • 您使用的 Python 版本不同。

标签: python linux python-3.x ubuntu pycharm


【解决方案1】:

可能在 IDE 之外的 Python2 下运行它,其中input 用于获取字符串评估它,就好像它是一个 Python 表达式一样。您似乎输入了单词add(因为这是您比较输入的内容之一),Python2 理所当然地抱怨它无法评估它。

Python 2 raw_input 等同于 Python 3 input,因此您可以使用它,或者确保它由 Python3 而不是 Python2 运行。

【讨论】:

  • 你是对的!我的终端使用的是 python 2.7 ......我之前没有注意到它!谢谢!
  • 我使用 'pyton3 main.py' 而不是 'python main.py' 来运行代码,它现在可以工作了!
猜你喜欢
  • 2019-05-23
  • 1970-01-01
  • 1970-01-01
  • 2014-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-26
相关资源
最近更新 更多