Is there a way to save data after it was printed to the screen?
for example:
lets have some arbitrary function
def main():
if something:
for i in range(n):
output= "%f %f" %(n,d)
print output
if something:
for i in range(n):
output="%f %f" %(n,d)
print output
fileout=open("data.csv", "a")
fileout.write(output)
this will only write the last data for the last range in for loop.
Edit: I want to ask a user if she/he wants to save that data
Declare your output variable(s) at the highest level of scope in your program first. This will allow it to be written to a file in the manner you've programmed.
If you want to prompt a user for a location to save the file(s), that's merely this:
out1 = raw_input("Where would you like to save this? ")
You can do the same for another output file variable.
just use this in the if conditions:
print >>fileout, output #this will save the output to the data.csv file
Change your code...
1: If you really want to use print, change sys.stdout to a different stream
2: use files
1
import sys
oldstdout=sys.stdout
f=open("myfile","w")
sys.stdout=f
def main():
if something:
for i in range(n):
print "%f %f"%(n,d)
if something:
for i in range(n):
print "%f %f"%(n,d)
2
f=open("myfile","w")
def main():
if something:
for i in range(n):
f.write("%f %f"%(n,d))
if something:
for i in range(n):
f.write("%f %f"%(n,d))
Here is a (somewhat pathological) example that will let you both print and save the statements that you print in a global list (which we'll call OUTPUT):
import sys
OUTPUT = []
def print_wrapper(method):
class result(object):
def __init__(self, file_obj):
self.file_obj = file_obj
def __getattr__(self, name):
return getattr(self.file_obj, name)
def write(self, value):
OUTPUT.append(value)
return self.file_obj.write(value)
return result(method)
original_stdout = sys.stdout
sys.stdout = print_wrapper(original_stdout)
# This will still print, but will add 'Hi' and '\n' to OUTPUT as well
print 'Hi'
# This will still print, but will add 'None' and '\n' to OUTPUT as well
print None
# This uses the original stdout to print, so won't change OUTPUT
original_stdout.write(repr(OUTPUT))
original_stdout.write('\n')
or you could alternately prepare yourself for Python 3 (or just use it) and wrap the print method itself:
from __future__ import print_function # must have Python >= 2.6
OUTPUT = []
def wrap_print(method):
def result(value):
OUTPUT.append(value)
return method(value)
return result
old_print = print
print = wrap_print(old_print)
print('Hi')
print(None)
old_print(OUTPUT)
Related
I want to check if a print statement is being called and add an additional print statement after it, without having to add an empty print statement manually after every instance.
My output is currently like this:
Hello
Hello
Hello
Hello
*(outputs this 10 times)*
while I would like it to look like this:
Hello
Hello
Hello
Hello
*(output 10 times as well in this pattern)*
I preferably want to use decorators as that is the easiest and best-looking solution, but another solution would also be okay!
I tried asking ChatGPT, but it doesn't change anything about the output.
Currently, this is my code:
def readability(func):
def wrapper(*args,**kwargs):
result = func(*args, **kwargs)
if callable(func) and func.__name__ == 'print':
print(' ')
return result
return wrapper
#readability
def printing():
j=10
while j>0:
print('hello')
j-=1
printing()
You could use contextlib.ContextDecorator to be able to use either a decorator or a context manager, which lets you control more finely where you want to use your modified print function.
In order to replace print, you just have to use print = your_own_function. You can still access the original print as __builtins__.print.
So, an example could be, with two sample personalized print functions which you can apply wherever you want: to a whole function using a decorator, or to a piece of code using a context manager:
from contextlib import ContextDecorator
def double_print(data):
__builtins__.print(data)
__builtins__.print()
def underlined_print(data):
__builtins__.print(data)
__builtins__.print('-'*len(str(data)))
class my_print_context(ContextDecorator):
def __init__(self, print_function):
self.print = print_function
def __enter__(self):
global print
print = self.print
return self
def __exit__(self, *exc):
global print
print = __builtins__.print
return False
def nums():
for i in range(3):
print(i)
We can use this like this:
#my_print_context(double_print)
def nums2():
for i in range(3):
print(i)
print('\nNormal')
nums()
print('\nDecorated')
nums2()
print('\nWith context manager')
with my_print_context(underlined_print):
print('Hello')
print('We are underlined')
nums()
print('\nAfter the context')
nums()
which outputs:
Normal
0
1
2
Decorated
0
1
2
With context manager
Hello
-----
We are underlined
-----------------
0
-
1
-
2
-
After the context
0
1
2
Original answer:
original_print = print
def print(*args):
original_print(*args)
original_print(' ')
print('Hello')
Improved answer using __builtins__:
def print(*args):
__builtins__.print(*args)
__builtins__.print(' ')
Both version produce the following output:
Hello
<blank line>
I am currently writing myself a program in python 3.7 and was wanting to add a timestamp to the front of my printing in the format:
<hh:mm:ss> WhateverImPrinting
I took a look at other forums and I get some code which used sys.stdout, overwriting the text using the write function.
My issue is it is returning the timestamp both before and after my print.
e.g. <14:21:51> Hello<14:21:51>
This should be:
<14:21:51> Hello
My code:
old_f = sys.stdout # Get old print output
class PrintTimestamp:
# #staticmethod
def write(self, x):
old_f.write("<{}> {}".format(str(pC.Timestamp.hhmmss()), x))
# #staticmethod
def flush(self):
pass
sys.stdout = PrintTimestamp() # Set new print output
I have run this after all my classes and functions, but before if __name__ == '__main__'
You can simply override print function in Python 3.x:
from datetime import datetime
old_print = print
def timestamped_print(*args, **kwargs):
old_print(datetime.now(), *args, **kwargs)
print = timestamped_print
then
print("Test")
should print
2019-09-30 01:23:44.67890 Test
Here you go.
from datetime import datetime
class PrintTimeStamp():
def write(self,x):
ts = str(datetime.now.hour())+":"+str(datetime.now().minute)+":"+str(datetime.now().second)
print("<{}> {}".format(str(ts),x)
pts = PrintTimeStamp()
pts.write("test")
i make a simple code in python to output data in txt format file in my local driver pc using windows OS but nothing happened . i want to know the problem
here is the code :
f = open("my.txt" , "w")
def a():
return (2+3)
def x():
b = a()
print("\n" ,b)
f.write(x())
f.close()
please try this
f = open("my.txt" , "w")
def a():
return (2+3)
def x():
b = a()
print("\n" ,b)
return str(b)
f.write(x())
f.close()
since function x does not return anything you cant print it to file
Writing into files both strings and variables.
Please Note: There are many ways to get it done. This is just one.
#!/usr/bin/env python
import sys
# function returning compute results
def fun_compute(num):
return num * num
# For writing in a file.
# Opened the file in w+ mode
with open("./files/sample.txt", "w+") as sys.stdout:
print("I am printing fun stuff!") # writing standard string
num = 5
for n in range(num):
print("fun_compute for - %s" % fun_compute(n))
I'm wishing to print a character to the start of every line in python code. In particular, I want to print a "|" to the start of every outputted line. What would be the best way to achieve this in python?
Using Python 3? Replace print:
_realprint = print
def print(*args, **kwargs):
_realprint('|', end='')
_realprint(*args, **kwargs)
print.__doc__ = _realprint.__doc__
Now everything output by print will be prefixed by '|'. Extra credit for replacing \n with \n| in your _realprint() calls, remembering when called with end equal to something other than \n, etc. This should get you through 99% of cases, though.
Make your own file-like that defines write() and replace sys.stdout.
import sys
class forewrap(object):
def __init__(self, origfile, cseq='|'):
self.file = origfile
self.cseq = cseq
self.seen = False
def write(self, txt):
if not (self.seen and txt == '\n'):
self.seen = True
self.file.write(self.cseq)
else:
self.seen = False
self.file.write(txt)
print 'foo'
sys.stdout = forewrap(sys.stdout)
print 'foo'
print
print 'bar'
I'm trying to learn programming through Python and I like to know if it's possible to get just the return value of a function and not its other parts. Here's the code:
Let's say, this is the main function:
variable_a = 5
while variable_a > 0 :
input_user = raw_input(": ")
if input_user == "A":
deduct(variable_a)
variable_a = deduct(variable_a)
else:
exit(0)
Then this is the deduct function:
def deduct(x):
print "Hello world!"
x = x - 1
return x
What happens is that, it does the calculation and deduct until variable_a reaches 0. However, "Hello world!" gets printed twice, I think because of variable_a = deduct(variable_a) (correct me if I'm wrong). So I was thinking, can I just capture the return value of deduct() and not capture the rest? So that in this instance, after going through deduct(), variable_a would just have a plain value of 2 (without the "Hello world!").
Am I missing things? :?
Editor's note: I remove the blank lines, so it can be pasted to REPL.
The printing of "Hello world" is what's known as a side effect - something produced by the function which is not reflected in the return value. What you're asking for is how to call the function twice, once to produce the side effect and once to capture the function return value.
In fact you don't have to call it twice at all - once is enough to produce both results. Simply capture the return value on the one and only call:
if input_user == "A":
variable_a = deduct(variable_a)
else:
If you don't want your function to print output, the correct solution is to not use print in it. :P
The first time you call deduct, it doesn't do anything except print that message, so you could probably just remove that line and be fine.
However, there is a slightly messy way to suppress print statements. You can temporarily replace your program's output file with a placeholder that does nothing.
import sys
class FakeOutput(object):
def write(self, data):
pass
old_out = sys.stdout
sys.stdout = FakeFile()
print "Hello World!" # does nothing
sys.stdout = old_out
print "Hello Again!" # works normally
You could even make a context manager to make this more convenient.
import sys
class FakeOutput(object):
def __enter__(self):
self.out_stdout = sys.stdout
sys.stdout = self
return self
def __exit__(self, *a):
sys.stdout = self.out_stdout
def write(self, data):
pass
print "Hello World!" # works
with FakeOutput():
print "Hello Again!" # doesn't do anything
print "Hello Finally!" # works