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)
Related
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. :)
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.
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))
in the following for loop, i print the version number of program installed
for program in sub3_required_programs:
try:
version = subprocess.call([program, '-i'])
print version + '\n'
except:
exit
But i actually want only the first line which has the version number. How can i restrict the print to only the first line
You can do:
print version.split("\n")[0]
which gets first line (splitting on newline character) from the output.
The problem with the str.split('\n') approach is that the newline character can differ across platforms. You might have better luck doing:
print version.splitlines()[0]
What's the current print output? Unless you're running a version of Python that behaves differently, it looks like the return status of the call is the only thing being assigned to version.
Run command with arguments. Wait for command to complete, then return
the returncode attribute.
- docstring for subprocess.call
I bet the subprocess.call is the culprit, printing it's output to STDOUT. Even if you didn't have that print statement, you would still see all the output of the subprocess call due to the way the method works.
To grab the actual output, you might want to do something more like
lines = subprocess.Popen([program, '-i'], stdout=subprocess.PIPE).communicate()[0]
print lines.splitlines()[0] + '\n'
The communicate call returns the tuple (stdoutdata, stderrdata). You can read more about it in the docs. Everything else should be self-explanatory.
Split the string at the newline character, and use only the first element of the resulting list:
print version.split('\n')[0]
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.