简体   繁体   中英

How can I execute this python program from mac terminal

I want to execute the following program called APlusB.py in my OSX terminal, enter two numbers for the inputs and have it compute the values and exit. In my terminal I type:

$ python3 APlusB.py

then I get a little cursor on a blank line, I type

3 4

what do I do after that? If I hit Ctl + d then the program terminates, which is what I want, but it prints 7D and I would prefer if it would just compute my value, and print out 7

# Uses python3
import sys
input = sys.stdin.read()
tokens = input.split()
a = int(tokens[0])
b = int(tokens[1])
print(a + b)

Thank you for your help.

sys.stdin.read waits for the user to enter EOF .

Try using input it will return when the user enters a new line. Don't name your variable input as you'll be redefining the input function you'll need to use.

Please use sys.stdin.readline()

stdin.read(1) reads one character from stdin. If there was more than one character to be read at that point (eg the newline that followed the one character that was read in) then that character or characters will still be in the buffer waiting for the next read() or readline() .

import sys
input = sys.stdin.readline()
tokens = input.split()
a = int(tokens[0])
b = int(tokens[1])
print(a + b)

the usage:

esekilvxen263 [7:05] [/home/elqstux] -> python wy.py
3 4
7
esekilvxen263 [7:06] [/home/elqstux] -> 

This is the best way to take in input. It is intended for Python 3.

tokens = input()
tokens = tokens.split()
a = int(tokens[0])
b = int(tokens[1]) 
print(a + b)
import sys
input = sys.stdin.read()
tokens = input.split()
a = int(tokens[0])
b = int(tokens[1])
print tokens
print(a + b)

If you put print tokens front print(a+b) .It works as you expect.

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