简体   繁体   中英

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 .

Example using 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

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:

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 . Optional arguments in argparse are prefixed by a double hyphen, an example shown below as shown in the python documentation.

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; you could opt to use input_val = input('Question here') .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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