简体   繁体   English

如何在脚本中读取标准输入?

[英]How to read stdin in a script?

import sys

def optimal_summands(n):
    summands = []
    sum = n
    i = 0
    while (sum > 0):
        if 2*(i+1) < sum:
            i+=1
            summands.append(i)
            sum-=i
        else:
            summands.append(sum)
            sum=0
    return summands

if __name__ == '__main__':
    input = sys.stdin.read()
    n = int(input)
    summands = optimal_summands(n)
    print(len(summands))
    for x in summands:
        print(x, end=' ')

I am having an issue running this with my own input. 我在使用自己的输入来运行时遇到问题。 I go to my terminal and type 我去终端输入

(ykp) y9@Y9Acer:~/practice$ python optimal_summands.py 15

and nothing happens. 并没有任何反应。

How am I supposed to run my own code on custom inputs? 我应该如何在自定义输入上运行自己的代码? This seems like something that should be simple but I have not seen an example of how to do this anywhere in the documentation. 这看起来应该很简单,但是我在文档的任何地方都没有看到如何执行此操作的示例。

I believe you might be after sys.argv or for more features you can opt for argparse . 我相信您可能在sys.argv之后,或者对于更多功能,您可以选择argparse

Example using sys.argv 使用sys.argv示例

if __name__ == '__main__':
    filename = sys.argv[0]
    passed_args = map(int, sys.argv[1:]) # if you're expecting all args to be int.
    # python3 module.py 1 2 3
    # passed_args = [1, 2, 3]

Example using argparse 使用argparse示例

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("n", type=int, help="Example help text here.")

    args = parser.parse_args()
    n = args.n
    print(isinstance(n, int)) # true

You can use argparse to supply your user with help too, as shown below: 您也可以使用argparse为用户提供帮助,如下所示:

scratch.py$ python3 scratch.py -h
usage: scratch.py [-h] n

positional arguments:
  n           Example help text here.

optional arguments:
  -h, --help  show this help message and exit

The above doesn't include the import statements import sys and import argparse . 上面的代码不包含import语句import sysimport argparse Optional arguments in argparse are prefixed by a double hyphen, an example shown below as shown in the python documentation. argparse中的可选参数以双连字符作为前缀,以下示例如python文档中所示。

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display a square of a given number")
parser.add_argument("-v", "--verbose", action="store_true",
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbose:
    print("the square of {} equals {}".format(args.square, answer))
else:
    print(answer)

If you're simply looking to expect input through CLI; 如果您只是希望通过CLI输入; you could opt to use input_val = input('Question here') . 您可以选择使用input_val = input('Question here')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM