How to avoid spaces with stdout in python? - python

While messing around with Python, I decided to make a random symbol generator, that would output a continuous stream of characters to the CL.
It's pretty simple, and looks like this:
from random import choice
import sys
char_ranges = [[33,48],[58,65],[91,97],[123,127]]
chars = []
for r in char_ranges:
for i in range(r[0],r[1]):
chars.append(chr(i))
while True:
print choice(chars),
sys.stdout.flush()
The only problem with it, is that the , used after printing a character causes a space to be added after stdout.flush() is called.
The way I'd usually get around this, is by concatenating a string and printing that instead, but in this case I want a continuous output flow, and therefore concatenation won't help.
So how can I get a continuous output flow in Python with no spaces?

Use sys.stdout.write instead of print.
print is a higher level construct for quick and dirty output. If you need more control, use something else.

Try this:
sys.stdout.write(choice(chars))

Related

Python treating carriage return as newline character. What can I do instead?

I want to write a code which prints Loading, and then erases that and prints Loading., erases that too and prints Loading.. and so on. So I tried using \r, but python interprets it as \n. Is there a charcter I can use instead of \r?
I've tried using \b instead, but Python doesn't recognize it, either. For example, if I print qwerty\buiop, it just prints qwertyuiop.
This is the code I tried, using carriage return:
import time
for y in range (5):
for i in range (4):
print("Loading","."*i, end="\r")
time.sleep(0.5)
However, instead of printing how I want it to, it prints like
Loading
Loading .
Loading ..
Loading ...
in different lines.
How do I solve this problem? Is there a different character I can use?
I'm using IDLE and MacOS.
Thank you so much!
I know you probably know an answer by now, but for people still looking for one:
Try using an empty end, while using \r at the beginning of each print to overwrite the previous one.
import time
for i in range (4):
print("\rLoading","."*i, end ="")
time.sleep(0.5)
Try running your program in terminal.
Different shells interpret the \r character in different ways. A lot of them will write out each print as a separate output rather than one ongoing stream. Terminal should interpret it the way you are thinking

Delete last printed character python

I am writing a program in Python and want to replace the last character printed in the terminal with another character.
Pseudo code is:
print "Ofen",
print "\b", # NOT NECCESARILY \b, BUT the wanted print statement that will erase the last character printed
print "r"
I'm using Windows8 OS, Python 2.7, and the regular interpreter.
All of the options I saw so far didn't work for me. (such as: \010, '\033[#D' (# is 1), '\r').
These options were suggested in other Stack Overflow questions or other resources and don't seem to work for me.
EDIT: also using sys.stdout.write doesn't change the affect. It just doesn't erase the last printed character. Instead, when using sys.stdout.write, my output is:
Ofenr # with a square before 'r'
My questions:
Why don't these options work?
How do I achieve the desired output?
Is this related to Windows OS or Python 2.7?
When I find how to do it, is it possible to erase manually (using the wanted eraser), delete the '\n' that is printed in python's print statement?
When using print in python a line feed (aka '\n') is added. You should use sys.stdout.write() instead.
import sys
sys.stdout.write("Ofen")
sys.stdout.write("\b")
sys.stdout.write("r")
sys.stdout.flush()
Output: Ofer
You can also import the print function from Python 3. The optional end argument can be any string that will be added. In your case it is just an empty string.
from __future__ import print_function # Only needed in Python 2.X
print("Ofen",end="")
print("\b",end="") # NOT NECCESARILY \b, BUT the wanted print statement that will erase the last character printed
print("r")
Output
Ofer
I think string stripping would help you. Save the input and just print the string upto the length of string -1 .
Instance
x = "Ofen"
print (x[:-1] + "r")
would give you the result
Ofer
Hope this helps. :)

Is it possible to print without using the print function in Python?

I wondered whether it is possible to print (for example a string) in Python without the print function. This can be done by a command or by some trick.
For example, in C there are printf and puts.
Can someone show me a way to print or to deny this possibility?
sys.stdout.write("hello world\n")
import sys
sys.stdout.write("hello")
You can use
sys.stdout.write()
Sometimes I find sys.stdout.write more convenient than print for printing many things to a single line, as I find the ending comma syntax of print for suppressing the newline inconvenient.

How to grab all the lines with readline function in python?

grabc is a tool for output the colour code and RGB value.
When I use it, the output looks like this.
$grabc
'#000051'
'0,0,81'
I used this program for grabbing the output
import os
p=os.popen('grabc')
s=p.readline()
p.close()
print "a="+s
>>> "a=#000051"
but I want
>>> "a=#000051
0,0,81"
as the output
what should I do to grab the second line.
I am using python. And I need to grab the whole output in a.
One way would be to use lines = p.readlines() instead. This will read not one, but all the lines from the output and return them as a list of strings. However, instead of os.popen you may want to use the corresponding functions of the newer subprocess module instead.
You can use "".join(lines) to join the list of strings to a single string. Since the lines still have their original line end character, you can just use "" as delimiter. Alternatively, you could strip the line end characters and use your own delimiter: "\n".join([l.strip() for l in lines]).
Also, note that you do not assign the output to the variable a at all, but just print it that way. Further, depending on what you want to do with the color values, it might be better to leave them separate and assign them to different variables instead.
Update: On closer inspection, it seems that not all the output of grabc is captured this way, neither with subprocess or even when doing grabc > some_file. The hex-string is captured, but the color tuple is not. However, you can easily convert one value into the other, so this should not be a problem.
h = "#a7bd7a"
t = 167,189,122
"#%02x%02x%02x" % t # color tuple to hex string
[int(h[i:i+2], 16) for i in range(1, len(h), 2)] # hex string to color tuple

how to remove unnecessary chars from date command output in python

I am new to python. Forgive me if it's too simple. I want to extract only date using date command in python
import subprocess
p = subprocess.Popen(["date", '+%m/%d/%y'], stdout=subprocess.PIPE)
output,err = p.communicate()
print (output)
Now this is printing
b'05/14/13\n'
How to remove the unnecessary '\n' and b at start.
>>> str(b'05/14/13\n').rstrip()
'05/14/13'
Speed comparisons:
>>> import timeit
>>> timeit.timeit(r"b'05/14/13\n'.decode('ascii').rstrip()")
0.7801015276403488
>>> timeit.timeit(r"str(b'05/14/13\n').rstrip()")
0.2503617235778428
Thomas's answer is correct, but I feel more explanation is necessary.
I always .decode('utf8') the result of p.communicate() or check_output() et al. This is because stdout/stdin is always opened in binary mode, unless you explicitly provide a file handle, so you always receive/send bytes, not str.
In this case, I suggest just using check_output(['date','+%m/%d/%y']) rather than creating a Popen object which you then basically throw away :)
So, I would suggest rewriting this to:
import subprocess
result = subprocess.check_output(['date', '+%m/%d/%y']).decode('utf8').rstrip()
print (result)
On a more meta level, there is a question of whether you even need to use subprocess for this task.
After all, there is time.strftime() for formatting dates/times. This:
import time
print(time.strftime('%m/%d/%y'))
achieves the intended effect of your entire program in a much simpler way.
Also from tink's comment:
import datetime
print datetime.date.today().strftime('%m/%d/%y')
b means it is a binary string, you can get a unicode string by output.decode('ascii'). To get rid of the trailing newline:
output = output.strip()
output = output.decode('ascii')
print(output)

Categories

Resources