将交互式输入程序更改为命令行输入

时间:2014-04-11 04:07:36

标签: python

我编写了一个程序,从用户那里收集一些数字并打印出最小的数字。这是该计划:

def main():
   numbers = eval(input("Give me an array of numbers: "))
   smallest = numbers[0]
   for i in range(0,len(numbers),1):
     if (numbers[i] < smallest):
        smallest = numbers[i]
   print("The smallest number is: ", smallest)
main()

现在从每个人的答案来看,我已经到了这一步。

导入系统 从列表导入*

def main():
   strings = ArrayToList(sys.argv[1:])
   numbers = ListMap(int,strings)
   smallest = numbers[0]
   for i in range(0,len(numbers),1):
      if (numbers[i] < smallest):
         smallest = numbers[i]
   print("The smallest number is: ", smallest)
main()

我收到错误:

File "command.py", line 12, in <module>
   main()
File "command.py", line 9, in main
   if (numbers[i] < smallest):
TypeError: unorderable types: list() < int()

现在我应该使用列表的极端模式来查找并打印ListMap将参数转换为整数后的最小整数。任何人都可以帮助我完成这个计划吗?

3 个答案:

答案 0 :(得分:0)

使用sys.argv:它会为您提供传递给程序的参数列表。

import sys

def main():
   # converts the argv strings into a list of int
   numbers = [int(arg) for arg in sys.argv[1:] # first value is the name of the program itself
   smallest = numbers[0]
   for i in range(0,len(numbers),1):
     if (numbers[i] < smallest):
        smallest = numbers[i]
   print("The smallest number is: ", smallest)
main()

现在真正的pythonic方式是:

import sys

if __name__ == '__main__':
    print(min([int(arg) for arg in sys.argv[1:]]))
  1. if __name__ == '__main__'是定义程序入口点的好方法,因为名称符号设置为' main '模块直接执行(不是从另一个模块)
  2. min(iterable)返回可迭代的最小值
  3. print()(不仅仅是打印)使它兼容python 3

答案 1 :(得分:0)

sys.argv是可行的方法:

示例程序:

import sys
print sys.argv[1:]

<强>运行:

$ python3 myscript.py this is cool
['this', 'is', 'cool']

您的脚本:

import sys

def main():
   numbers = sys.argv[1:]
   smallest = numbers[0]
   for i in range(0,len(numbers),1):
     if (int(numbers[i]) < smallest):
        smallest = (numbers[i])
   print("The smallest number is: ", smallest)
main()

运行方式:

$ python3 myscript.py 11 5 3 51
The smallest number is: 3
$

要转换为整数,请键入int(variable),只需使用int()

包围变量

答案 2 :(得分:0)

使用argparse模块处理命令行输入。使用它并不困难,它为您提供了解析简单输入(例如整数列表)的好处。

import argparse

parser = argparse.ArgumentParser(  # this is the main class of argparse
    description='collect some numbers and print out the smallest')
parser.add_argument(
    'numbers',    # the name of this command line argument 
    nargs='+',    # this '+' means it can be repeated (appear multiple times)
    metavar='N',  # the name to call this argument on help messages
    type=int,     # after parsing, the argument will be of type list<int>
    help='a number to search the minimum in')
# when you are done describing the arguments to the parser, tell it to parse
args = parser.parse_args()

# and here is a simplification of your function using the built-in `min`
print(min(args.numbers))  

像这样使用:

$ python3 main.py 1 2 3 4                                                                 ⏎
1