Python in raw mode stdin print adds spaces
Looks like you are only doing a line feed but no carriage return. Change your print to
print("ASD", end="\r\n")
Issue printing out to terminal with correct format
The problem occurs here:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
The tty is set to raw mode and then told to wait to read a char. While this thread is waiting for input, the other thread continues to output. It continues to output with the tty in raw mode. You can check this is the error by changing getchr() to just
def getchr():
tty.setraw(sys.stdin.fileno())
exit(0)
This will put the tty in raw mode and then kill the thread immediately. Using this, you will still get the same, undesired output even though only 1 thread is running.
The easiest fix would be to use a method from here.
Printing unescaped white space to shell
do you want a raw string ?
s = r"This string has \n\r whitespace"
or to transform special characters to it's representation?
repr(s)
How to simply read in input from stdin delimited by space or spaces
Python doesn't special-case such a specific form of input for you, but it's trivial to make a little generator for it of course:
def fromcin(prompt=None):
while True:
try: line = raw_input(prompt)
except EOFError: break
for w in line.split(): yield w
and then, in your application code, you loop with a for
statement (usually the best way to loop at application-code level):
for w in fromcin():
dosomething(w)
Cannot distinguish between up/down arrow in stdin raw mode
For arrow keys, buffer is a bit different : there are 3 bytes.
I have no idea what they represent, but i just know you have to get the third char :
process.stdin.setRawMode(true)
process.stdin.on('data', (data) => {
const str = data.toString();
if (str.length == 3) {
console.log(str.charCodeAt(2))
}
})
Arrow codes :
Up -> 65
Down -> 66
Right -> 67
Left -> 68
Print \n or newline characters as part of the output on terminal
Use repr
>>> string = "abcd\n"
>>> print(repr(string))
'abcd\n'
How to read multiple lines of raw input?
sentinel = '' # ends when this string is seen
for line in iter(input, sentinel):
pass # do things here
To get every line as a string you can do:
'\n'.join(iter(input, sentinel))
Python 2:
'\n'.join(iter(raw_input, sentinel))
Why does Python's print function act this way?
Because the print
statement adds spaces between separate values, as documented:
A space is written before each object is (converted and) written, unless the output system believes it is positioned at the beginning of a line.
However, "Hello" "World"
is not two values; it is one string. Only whitespace between two string literals is ignored and those string literals are concatenated (by the parser):
>>> "Hello" "World"
"HelloWorld"
See the String literal concatenation section:
Multiple adjacent string literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation.
This makes it easier to combine different string literal styles (triple quoting and raw string literals and 'regular' string literals can all be used to create one value), as well as make creating a long string value easier to format:
long_string_value = (
"This is the first chuck of a longer string, it fits within the "
'limits of a "style guide" that sets a shorter line limit while '
r'at the same time letting you use \n as literal text instead of '
"escape sequences.\n")
This feature is in fact inherited from C, it is not a Python invention.
In Python 3, where print()
is a function rather than a statement, you are given more control over how multiple arguments are handled. Separate arguments are delimited by the sep
argument to the function, which defaults to a space.
In Python 2, you can get the same functionality by adding from __future__ import print_function
to the top of your module. This disables the statement, making it possible to use the same function in Python 2 code.
Related Topics
How to Make Sure If Some HTML Elements Are Loaded for Selenium + Python
How to Install and Import Python Modules at Runtime
Translating Function for Finding All Partitions of a Set from Python to Ruby
Pandas Add Column to Groupby Dataframe
How to Print a String at a Fixed Width
Find Shortest Matches Between Two Strings
How to Allow or Deny Notification Geo-Location Microphone Camera Pop Up
How to Access a Dictionary Element in a Django Template
Python Referencing Old Ssl Version
How to Find Children of Nodes Using Beautifulsoup
How to Build 32Bit Python 2.6 on 64Bit Linux
Why Are Scripting Languages (E.G. Perl, Python, and Ruby) Not Suitable as Shell Languages
Negative Integer Division Surprising Result
Pandas: Rolling Mean by Time Interval
Is There a Decorator to Simply Cache Function Return Values
Some Unix Commands Fail with "<Command> Not Found", When Executed Using Python Paramiko Exec_Command