This question already has answers here:
What is the best way to toggle python prints?
(6 answers)
Closed 7 years ago.
I have 10 or 15 very useful debugging print statements sprinkled throughout my program (in different functions and in main).
I won't always want or need the log file though. I have a config file in which I could add a parameter to toggle print statements on or off. But then, I'd have to add a guard check for the value of this parameter above every print statement.
What are some better approaches?
from __future__ import print_function
enable_print = 0
def print(*args, **kwargs):
if enable_print:
return __builtins__.print(*args, **kwargs)
print('foo') # doesn't get printed
enable_print = 1
print('bar') # gets printed
sadly you can't keep the py2 print syntax print 'foo'
Related
This question already has answers here:
Why is "None" printed after my function's output?
(7 answers)
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed last year.
This post was edited and submitted for review last year and failed to reopen the post:
Original close reason(s) were not resolved
I have been trying to get this to output correctly. It is saying I'm not adding a line break at the end.
I was wondering, how I could add the line break? From my understanding the code is for the most part right.
I also need to have it take in another output that Zybooks generates itself, so I can't just simply put two print statements of ('*****')
def print_pattern():
print('*****')
for i in range(2):
print(print_pattern())
Expected output:
*****
*****
My output:
*****
None
*****
None
If you want your function to work, you have to return a value like this.
def print_pattern():
return '*****'
for i in range(2):
print(print_pattern())
You function isn't working properly because you are trying to print something that has no return value. If you return something and try to print like I have done in my code here, it will work.
Edit.
Since you cannot change the print_pattern() function, the correct way to do this would be like this.
def print_pattern():
print('*****')
for i in range(2):
print_pattern()
You just do a for loop where you run the function at the end of each loop. The print function my default adds a new line at the end of the print.
This question already has answers here:
How to print without a newline or space
(26 answers)
How can I flush the output of the print function?
(13 answers)
Closed 2 years ago.
im a beginner at python and i've come across what is probably a simple problem.
I want the code below to print the "." x times, each .100 of a second after each other. This is what ive got, but it just prints it all at once after x * .100 seconds. It would also help if you could redirect me to something that explains why it dosnt work or if you explained why it dosnt work.
import time
for i in range(x):
print(".", end="")
time.sleep(.100)
Thanks in advance.
PS. If the code is completely wrong please say so.
Just printing doesn't mean that the content is flushed - i.e. it can still be in a buffer in your terminal or execution environment.
You can append flush=True to the arguments to print in python3 to make it flush the output as well:
import time
for i in range(x):
print(".", end="", flush=True)
time.sleep(.100)
This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 3 years ago.
I am making a command line game engine in python. However, when I attempt to print a command, it newlines and creates a jittery frame.
Adding the end attribute bogs down my computer and nearly crashes the shell. The dupe uses sys.stdout.write('') newline sys.stdout.flush or print'', or print('',end=''). all bog down shell and crash it. print('') doesn't bog down though which is weird.
#this is enough code to demonstrate the problem
while true:
print(' = === ===== ======= ========= =========== ============= YYYYYYYYYYY ================================================================================')
#crash issue
import sys
while True:
sys.stdout.write('mooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo')
sys.stdout.flush()
I expect the screen to fill, instead it wobbles up and down.
I am not sure if I understood your question correctly, but I’m thinking you do not want to print a new line with each call to the print() function.
If so, the print function has an optional argument end, that is set by default as \n (this, creating a new line if not specified otherwise). If you don’t want this to happen, you can simply use the print function as:
print(your_argument, end=“”)
Replacing your_argument with whatever you want to print out.
This question already has answers here:
How to clear the interpreter console?
(31 answers)
Clear terminal in Python [duplicate]
(27 answers)
Closed 3 years ago.
I am running on Python 3.7.1 and I've been trying to find a way to clear a screen of any previously printed messages. The problem is that os.system("cls") does nothing, it only makes a small window pop up for a fraction of a second, then it closes. I've tried to add a \n at the end and multiplying it by how many letters there are, still not working.
Unfortunately, there’s no built-in keyword or function/method to clear the screen. So, we do it on our own.
We can use ANSI escape sequence but these are not portable and might not produce desired output.
# import only system from os
from os import system, name
# import sleep to show output for some time period
from time import sleep
# define our clear function
def clear():
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux(here, os.name is 'posix')
else:
_ = system('clear')
# print out some text
print('hello geeks\n'*10)
# sleep for 2 seconds after printing output
sleep(2)
# now call function we defined above
clear()
I don't think that there is a way, or at least have never seen one. However, there is a workaround which would look like
print "\n" * 100.
This will simply print 100 newlines, which will clear the screen for you.
You could also put it in a function
def cls(): print "\n" * 100
And then when you need it just call it with cls()
This question already has answers here:
Thread that I can pause and resume?
(2 answers)
Closed 4 years ago.
I would like to stop a running thread from outside a class, how it's possible
For example I have that broadcasting thread:
class BroadcastThread(Thread):
def __init__(self, converter, websocket_server):
super(BroadcastThread, self).__init__()
self.converter = converter
self.websocket_server = websocket_server
self.bRun = False
def run(self):
try:
while self.bRun:
print(self.bRun)
buf = self.converter.stdout.read1(32768)
if buf:
self.websocket_server.manager.broadcast(buf, binary=True)
elif self.converter.poll() is not None:
break
finally:
self.converter.stdout.close()
and I use it as follows from another class
self.broadcast_thread = BroadcastThread(self.output.converter, websocket_server)
and I need to start and stop it using the following methods
def start_broadcast_stream(self):
self.broadcast_thread.bRun = True
def stop_broadcast_stream(self):
self.broadcast_thread.bRun = False
The variable bRun is not updated at all by using the functions start_broadcast and stop
That is the common way in python and should work, but it will have the chance of stopping only every time the condition of the while is evaluated. You must guarantee the inside of the loop does not block, or takes very long time to run.
If you want to be able to cancel inside the loop, you need to slice things thinner (for example read 10 times a 1/10th of the data) and intercalate several checks of the bRun condition + breaks between them. Not pretty...
Edit: For added safety, bRun could be a Threading.Event, but I don't see the problem in this simple case.