I am trying to refactor a large source base in a company I work in. Instead of using the print function in python 2.7x I want to use the logger function.
for example:
print "Sample print %d" % timestamp
With logger.info("Sample print %d" % timestamp)
so basically, I want to remove the print , and insert what remains into parentheses and logger.info (Ill assume all current prints are INFO until a full refactor is possible).
Thanks in advance
Search for (^\s+)print (.*)$
Replace with $1logger.info($2)
Python should complain pretty fast about all the places where a print goes over more than a single line. You'll have to fix those places manually.
Note: This skips comments
The alternative is to look into the source for 2to3.py which replaces print ... with print(...) to convert code from Python 2 to 3.
Related
I am writing a short Python 3 program that takes a Python 2 script, and fixes the way Python 2's printing function worked, and fixes it to make it work with Python 3. This is useful for some scripts that use Python 2, but the only issue is that there's tons of incorrect examples of printing according to Python 3.
Example:
Let's say I have a Python 2 script that looks like this:
print 'hello world'
I would want to use my program to convert it to this:
print('hello world')
So far, I have this, which strips the new lines, replaces the first instance of the quotation mark with an opening parenthesis, and replaces the second instance of the quotation mark with a closing parenthesis.
if "print" in ReadNextLine:
RawInput = ReadNextLine.replace(" ", "")
ReadyForFixing = RawInput.strip("\n")
replaceportion1 = ReadyForFixing.replace("'", "(", 1)
replaceportion2 = replaceportion1.replace("'", ")")
print(replaceportion2)
Output:
print(Line1)
print(Line2)
print(Line3)
print(Line4)
print(Line5)
I was wondering if there was some way to insert a quotation mark after the first parenthesis, and before the second parenthesis.
Keep in mind that these outputs will be dynamic according to whatever the file that the user needs fixed inputs.
I plan on posting this project on Github. Let me know if you would like any crediting, since you may have technically collaborated.
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 have the following MWE:
import string
class MyTemplate(string.Template):
delimiter = '$'
pattern = r'''
\$(?:
(?P<escaped>\$)|
(?P<named>[_a-z][_a-z0-9]*)\$|
(?P<braced>[_a-z][_a-z0-9]*)\$|
(?P<invalid>)
)
'''
data1="max=$max$ min=$min$"
data2="max=$max$ "
print MyTemplate(data1).substitute({"max":"10","min":"1"})
print MyTemplate(data2).substitute({"max":"10","min":"1"})
print MyTemplate(data1).substitute({"max":"10"})
Of the 3 prints, I want that the only acceptable case is the first;
the last one raise an exception, but the second simply writes:
max=10
How can I detect this case (more values than placeholder)?
Is it possible to verify that a value is substituted only once?
Thanks!
The real questions here are "what are you trying to achieve?" and "is it needed?" and "why is it needed?"
If you still need it after answering all this, then override substitute in your MyTemplate class. You'll be able to do any check you like. It might slow down your program, though.
On the other hand, string.Template (from python 2.6) are mostly used through mystr.format(). And then, replaced by f-strings (3.6) https://www.python.org/dev/peps/pep-0498/
I'm new to python, I've only been using it for about 5 months but I'm ambitious and am currently working on a project to help me in the long run in terms of GCSEs.
print PercentComplete, "% complete"
I want to remove the space so instead of it printing "6.66 % complete", it would print "6.66% complete"
Many thanks
Miles
Use string formatting - it's much more flexible and robust. In this case:
print "{}% complete".format(PercentComplete)
do print str(PercentComplete)+"% complete"
In your answer, you were printing two different things. Here you combine it into one item and print it
A common way to do it is using string format.
print('%.2f %% complete' % PercentComplete)
This way you always will have the number correctly formatted.
The output will be
6.66% complete
I'm teaching myself Python and can't see a huge difference between these two examples except the extra formatting options (eg. %r) that string formatting provides.
name = "Bob"
print "Hi, my name is %s." % name
print "Hi, my name is", name
Is there any reason in general why you'd prefer one over the other?
I realise that .format() is the preferred way to do this now, but this just for me to better understand how Python operates.
The primary difference between the two (which no one else seems to be describing) is this:
print "Hi, my name is %s." % name
Here, a new string is being constructed from the two strings (the string literal and the value of name). Interpolation (the % operator) is an operation you could use anywhere—for example, in a variable assignment or a function call—not just in a print statement. This newly-minted string is then printed (then discarded, because it is not given a name).
print "Hi, my name is", name
Here, the two strings are simply printed one after the other with a space in between. The print statement is doing all the work. No string operations are performed and no new string is created.
It is programming choice:
1) Using % clarifies the type to the reader of the code, but for each additional variable used, the programmer will need to spend time in modifying in 2 places
2) Using , implicitly does % so the reader will have to look back to know about he type. But it is quick and if code is intuitively written removes a lot of burdon of maintenance
So yes, it is choice of maintaining balance between, maintenance, readability and convenience.
The difference is that the comma is part of the print statement, not of the string. Attempting to use it elsewhere, e.g. binding a string to a name, will not do what you want.