Is it possible to print without using the print function in Python? - 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.

Related

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. :)

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)

Python print skip arguments

I have this dirty short line of code printing a formatted date:
print '%f %d' % math.modf(time.time())
Now the modf method gives back two arguments, so the print function expects both. In the sake of purely doing this, and not the simple alternative of putting the output separately in a variable; is there any existing way of excepting parameters in print or is there any way to call specific argument-indexes?
For example I have 3 arguments in a print:
print '%s %d.%f' % 'Money',19,.99
I want to skip the first String-parameter that is parsed. Is there any way to do this?
This is mainly a want-to-know-if-possible question, no need to give alternative solutions :P.
Not in "old school" string formatting.
But the format method of strings does have this ability.
print "{1}".format ("1","2")
The above will skip the "1" and will only print "2".
I hope you don't mind I gave an alternative despite you not asking for it :)

How to avoid spaces with stdout in 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))

Quote POSIX shell special characters in Python output

There are times that I automagically create small shell scripts from Python, and I want to make sure that the filename arguments do not contain non-escaped special characters. I've rolled my own solution, that I will provide as an answer, but I am almost certain I've seen such a function lost somewhere in the standard library. By “lost” I mean I didn't find it in an obvious module like shlex, cmd or subprocess.
Do you know of such a function in the stdlib? If yes, where is it?
Even a negative (but definite and correct :) answer will be accepted.
pipes.quote():
>>> from pipes import quote
>>> quote("""some'horrible"string\with lots of junk!$$!""")
'"some\'horrible\\"string\\\\with lots of junk!\\$\\$!"'
Although note that it's arguably got a bug where a zero-length arg will return nothing:
>>> quote("")
''
Probably it would be better if it returned '""'.
The function I use is:
def quote_filename(filename):
return '"%s"' % (
filename
.replace('\\', '\\\\')
.replace('"', '\"')
.replace('$', '\$')
.replace('`', '\`')
)
that is: I always enclose the filename in double quotes, and then quote the only characters special inside double quotes.

Categories

Resources