【问题标题】:Read a data from terminal within a script从脚本中的终端读取数据
【发布时间】:2018-06-21 13:51:35
【问题描述】:

我想通过运行脚本从终端读取变量。 这是我的 script.py:

while True:
  value = input('enter text: ')
  if value == 'stop':
    print('bye-bye')
    break
  else:
    print('continue!')

但是,当我运行python script.py 时,发生了一些奇怪的事情。 如果我输入 int-data(例如 1,2,3),就没有问题。 如果我输入“停止”,我就会收到一个错误:

SyntaxError: invalid syntax

【问题讨论】:

  • 我运行这个,它适用于stop
  • 什么是完整的错误回溯?
  • Command-line input causes SyntaxError 的可能重复项----您正在运行 python 2,因此您需要 raw_input。这是python 3代码,其中raw_inputinput替换。
  • 谢谢,但真的吗?我不能。你知道如何在评论中发图片吗?
  • input text:'stop' Traceback(最近一次调用最后):文件“test.py”,第 11 行,在 value = input('input text:') File "",第 1 行“停止”^

标签: python


【解决方案1】:
def console(input_):
    input_ = input(r'Enter text: ')
    if input_ == str(r'stop'):
        return ("BYE BYE")
    else:
        input_ = input('continue')
    console(input_)

console(input)

在 python3 上运行良好。

【讨论】:

    【解决方案2】:

    您可能正在使用 Python2。在 Python2 中,input() 返回一个int,对于拥有string,你应该使用raw_input()

    while True:
      value = raw_input('enter text: ')
      if value == 'stop':
        print('bye-bye')
        break
      else:
        print('continue!')
    

    不要在 Python2 中使用input(),因为它实际上会评估输入,这可能很危险。与 Python3 和 Python2 input() 的区别参见this other question

    更改为raw_input()时,调用脚本前一定要保存

    【讨论】:

    • 接受对您有帮助的答案,或者创建一个新答案并接受:)
    猜你喜欢
    • 1970-01-01
    • 2014-12-08
    • 2013-10-06
    • 2013-05-14
    • 2015-12-08
    • 2020-03-08
    • 2020-01-16
    • 2021-05-23
    • 1970-01-01
    相关资源
    最近更新 更多