如何在命令行程序中输入循环值?

问题描述 投票:0回答:1

假设我有一个在zsh中运行的程序。

它接受一些命令,比如类型i + numberEnter键意味着在数据结构中插入一个数字并等待下一个输入。

我需要输入这么多数字来测试bug,这很费时间。所以我想编写一个shell脚本来创建一个可以自动完成的循环。我已经检查了一些文档,但没有找到在程序提示符下运行脚本的正确方法。

我的意思是现在程序已经运行并等待我定义的命令,如何使用脚本操作终端中的输入?

附: 我的英语不是那么好,所以我的描述可能有点误导:(,Kind Stack Overflowers,任何人都可以提供帮助吗?

Python有os模块,我试过并失败了。

我不想直接在程序代码中编写循环。

python shell
1个回答
0
投票

我认为这一定是你想要完成的事情:

how_many = int(input('How many numbers do you want to append to the list? '))
a_list = []

for i in range(how_many):
    number = int(input('Enter a number: '))
    a_list.append(number)

print("The list is: {}".format(a_list))

在你的shell中,你可以像这样运行它:

> python .\test.py
How many numbers do you want to append to the list? 2
Enter a number: 10
Enter a number: 20
The list is: [10, 20]

如果你想从文件中获取输入,你可以尝试这样的事情:

import sys

in_file = sys.argv[1]    
a_list = []

with open(in_file) as f:
    for line in f:
        print("The numbers in the line: {}".format(line))        
        numbers = line.split(',')
        for num in numbers:
            a_list.append(int(num.strip()))

print("Done appending the numbers to the list.")
print("The list is: {}".format(a_list))

在shell中尝试:

> python test.py nums.txt
The numbers in the line: 1, 2, 3, 4, 5
Done appending the numbers to the list.
The list is: [1, 2, 3, 4, 5]

nums.txt文件有这一行:1, 2, 3, 4, 5

© www.soinside.com 2019 - 2024. All rights reserved.