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.

martineau
  • 119,623
  • 25
  • 170
  • 301
Kashif
  • 3,063
  • 6
  • 29
  • 45
  • 1
    `15` is a command line argument, not something on standard input. – chepner Apr 24 '19 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. – Kit. Apr 24 '19 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 – juanpa.arrivillaga Apr 24 '19 at 21:22
  • Related - https://stackoverflow.com/questions/17658512/how-to-pipe-input-to-python-line-by-line-from-linux-program – OneCricketeer Apr 24 '19 at 21:31
  • So what’s the point of stdin if I can’t use terminal input? How would I provide data to stdin? – Kashif Apr 24 '19 at 23:10
  • I also ran python optimal_summands.py, pressed enter, and then typed in 15 (that should have been processed as stdin). Nothing happened still. – Kashif Apr 24 '19 at 23:16
  • See [here](https://en.wikibooks.org/wiki/Python_Programming/Input_and_Output) – Kit. Apr 25 '19 at 00:20
  • Thanks but this doesn't help. I need an example of how I use terminal with sys.stdin.read(). – Kashif Apr 25 '19 at 13:32
  • It is written there (`Note that sys.stdin.read() will read from standard input till EOF. (which is usually Ctrl+D.) `). If it doesn't help you, i am sorry. – Kit. Apr 26 '19 at 17:25
  • Oh I see -- yes it helps now. I didn't know terminal input was considered standard input. Sorry I'm just very new to this stuff. – Kashif Apr 26 '19 at 23:23

1 Answers1

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

Julian Camilleri
  • 2,975
  • 1
  • 25
  • 34
  • Thank you. So is there a way for me to do anything similar using `sys.stdin.read()`? Or no. – Kashif Apr 25 '19 at 13:07
  • No. - https://stackoverflow.com/questions/29454365/what-does-sys-stdin-read give this a read my friend. – Julian Camilleri Apr 25 '19 at 15:25
  • 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. – Kashif Apr 25 '19 at 20:14
  • 1
    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. – Julian Camilleri Apr 26 '19 at 12:40
  • 1
    Awesome -- this is extremely helpful. I couldn't find this explanation anywhere else online, which is shocking to me. – Kashif Apr 26 '19 at 14:40
  • You're welcome, maybe you looked at the wrong places. - if it answers your question @Glassjawed don't forget to mark it as the correct answer. Good luck with your learnings (; – Julian Camilleri Apr 27 '19 at 13:43