简体   繁体   English

我如何从Mac终端执行此python程序

[英]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. 我想在OSX终端中执行以下程序,称为APlusB.py,输入两个数字并让其计算值并退出。 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 如果我按Ctl + d键,程序将终止,这是我想要的,但是它会打印7D,我希望它只计算我的值,然后打印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 . sys.stdin.read等待用户输入EOF

Try using input it will return when the user enters a new line. 尝试使用input ,当用户输入新行时它将返回。 Don't name your variable input as you'll be redefining the input function you'll need to use. 不要命名变量输入,因为您将重新定义需要使用的输入函数。

Please use sys.stdin.readline() 请使用sys.stdin.readline()

stdin.read(1) reads one character from stdin. stdin.read(1)从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() . 如果此时要读取的字符不止一个(例如,换行后跟读入的一个字符),则该一个或多个字符仍将在缓冲区中,等待下一个read()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. 它适用于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. 如果您将print tokens放在print(a+b)前面,它将按预期工作。

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

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