Question: Question:
Is there a way to prevent line breaks when inputting with input () in Python3?
When the input is 3, the desired output result looks like the following.
| x | *2 | *4 |
a | 3 | 6 | 12 |
The current situation is as follows.
| x | *2 | *4 |
a | 3
| 6 | 12 |
Answer: Answer:
First, input () does not output a line break, but a line break occurs because the terminal echoes what the user is inputting a line break (output so that the content entered by the user can be confirmed). To do.
Therefore, the line feed output for the user's line feed can be suppressed only by changing the terminal settings.
The following code will behave like that in an environment that supports the termios module. (It doesn't work with Python for Windows or IDLE. I think it works with Python for cygwin on Windows)
import termios
import sys
import os
class KeyScanner:
def __enter__(self):
self.fno = sys.stdin.fileno()
# backup current settings
self.termattr_backup = termios.tcgetattr(self.fno)
new_attr = termios.tcgetattr(self.fno)
new_attr[3] &= ~termios.ECHO # no echo
new_attr[3] &= ~termios.ICANON # no canonical
termios.tcsetattr(self.fno, termios.TCSADRAIN, new_attr)
return self
def __exit__(self, *args):
# restore old settings
termios.tcsetattr(self.fno, termios.TCSANOW, self.termattr_backup)
def readInt(self):
number_text = ''
c = sys.stdin.read(1)
while True:
if c == '\n':
break
elif c.isdigit():
sys.stdout.write(c)
sys.stdout.flush()
number_text += c
c = sys.stdin.read(1)
if number_text.isdigit():
return int(number_text)
else:
return None
if __name__ == "__main__":
with KeyScanner() as scanner:
print(" | x | *2 | *4 |")
print("a | ", end='', flush=True)
x = scanner.readInt()
if x:
print(" | {:>2} | {:>2} |".format(x*2, x*4))
else:
print("\nNO INPUT ERROR!")