如何在Python控制台中一次输入多个命令

3

我想一次性在Python控制台中输入多个命令以进行测试。
例如:

userInput = None
while userInput != 'end':
    userInput = input('$ ')
    userInput = userInput.strip()
    if userInput == 'one':
        print('all')
    elif userInput == 'two':
        print('at')
    elif userInput == 'three':
        print('once')

有没有可能在输入“one”后,不再触摸键盘,然后输入“two”和“three”呢?
类似于:

one\rtwo\rthree\r

感谢您的帮助!
3个回答

2

有时候我喜欢修改input以便在IDLE中按下F5测试。 在您的情况下,您可以在代码之前添加以下内容:

def input(prompt, inputs=iter('one two three end'.split())):
    x = next(inputs)
    print(prompt + x)
    return x

那么您就不需要输入任何内容。输出结果为:
$ one
all
$ two
at
$ three
once
$ end

1

只需创建一个名为input.txt的文本文件,内容如下:

one
two
three
end

并像这样调用您的脚本:

python myscript.py < file.txt

我想补充一点。你甚至可以使用“>”而不是“<”将内容写入文件而非shell。它们将标准输入和输出重定向到指定的文件。你也可以在许多实用程序中使用这个功能。 - Abhirath Mahipal
1
你说得对。特别是在测试时,我们需要记录输出结果。我有点羞愧地回答了这么基础的问题,但是嘿,人们总得有学习的方式,不是吗? - Jean-François Fabre
当我在一个四行程序中花了 20 到 30 分钟仍无法找到语法错误时,我问了一个非常简单的问题。当有人给我提供解决方案时,我感到非常欣慰 :) - Abhirath Mahipal

1
我建议从 @Jean-Francois Fabre 和 @Abhirath Mahipal 获取输入。
但这只是另一个选项,如果你的输入有限。
userInput = raw_input('$ ')
userInput = userInput.strip()
for each in userInput.split('\\r'):
    if each == 'one':
        print('all')
    elif each == 'two':
        print('at')
    elif each == 'three':
        print('once')
    elif each == 'exit':
        break

这是执行过程:
python test.py
$ one\rtwo\rthree\rexit
all
at
once

注意:Python 3 用户应将 raw_input 替换为 input

代码可以运行,但我认为你误解了用户的意图。他想要一个真正的“回车”,而不仅仅是 '\r'。但由于在这种情况下需要一个分隔符,所以它可以是任何东西,所以我不会给你点踩 :) 我甚至改进了你的答案:现在Python 3是标准,raw_input已经不存在了,在Python 3中,input完全相同。 - Jean-François Fabre
@Jean-FrançoisFabre 谢谢,我理解你的观点,也感谢你的编辑。 - be_good_do_good

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接