2
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.

10
  • 1
    15 is a command line argument, not something on standard input. Commented Apr 24, 2019 at 21:20
  • 2
    15 in your case is not in stdin, but in argv. That "nothing happens" is probably a program waiting for your input. Commented Apr 24, 2019 at 21:21
  • 1
    You haven't provided anything to the standard input of the process, so sys.stdin.read() is going to hang, waiting for an EOF from stdin Commented Apr 24, 2019 at 21:22
  • Related - stackoverflow.com/questions/17658512/… Commented Apr 24, 2019 at 21:31
  • So what’s the point of stdin if I can’t use terminal input? How would I provide data to stdin? Commented Apr 24, 2019 at 23:10

1 Answer 1

3

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').

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you. So is there a way for me to do anything similar using sys.stdin.read()? Or no.
So it seems like to use sys.stdin.read(), I have to enter in my arguments after I run python optimal_summands.py and then do CTRL+D (in Linux) for EOF.
Usually sys.stdin.read is used to read data from a file using something like python3 script.py < textfile.txt - that's the only use case I've come up with needing in the past. Although you might possibly want to use something like: input('Number of summands you'd like to choose.') which will ask the user to enter the number in the CLI.
Awesome -- this is extremely helpful. I couldn't find this explanation anywhere else online, which is shocking to me.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.