When is a variable released from memory? [duplicate] - python

This question already has answers here:
when does python delete variables?
(4 answers)
Closed 7 years ago.
Say I define a function, which builds a list, and then prints the items of the list one by one (no practical use, just an example:
import os
def build_and_print():
thingy = os.walk('some directory')
for i in thingy:
print i
if __name__ == '__main__:
build_and_print()
If the thingy that is built is very large it could take up a lot of memory, at what point will it be released from memory?
Does python store the variable thingy until the script is finished running or until the function that builds/uses it is finished running?

Once a Variable goes out of scope, it is collected by the garbage collector.
You can see the collector code here. Go to collect function, there comments explain the process well.

Related

Is there a way to make an infinite loop in python? [duplicate]

This question already has answers here:
Infinite for loop in Python like C++
(6 answers)
Closed 1 year ago.
I know you can just do this (technically):
import time
variable = 0
while variable < 99999999999999999999999999999999999999
variable = variable + 1
time.sleep(1)
But is there just a way to make an infinite loop without typing all those 9's?
(idk if this makes sense but I'm sure you get what I mean)
You can use
import time
while True:
time.sleep(1)
Because you want an infinite loop with a one-second delay between iterations.

Is there a way to prevent automatic newline on python command line? [duplicate]

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.

how stop a running thread safely in python [duplicate]

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.

Python: Global Object Destruction [duplicate]

This question already has answers here:
Python how to ensure that __del__() method of an object is called before the module dies?
(3 answers)
Closed 8 years ago.
I have a global instance, which I expect to be destroyed (function __del__ called) when the Python interpreter exits. Am I expecting too much of the Python interpreter?
My method of testing this is to put a print in the __del__ function, run python.exe from a command line, and then pressing Ctrl/Break. At this point, I would expect to see the print in the command-line window. However, I do not.
Yes, you're expecting too much. Python doesn't make any guarantees about calling __del__:
It is not guaranteed that __del__() methods are called for objects that still exist when the interpreter exits.
Edit:
Generally, you should avoid using __del__. For most cases context managers are better. For the rare case when you need to make sure that some external (i.e. allocated from C code) resource gets cleaned up when the interpreter exits you can use the atexit module.
You could add a handler for the signal.SIGBREAK signal. That would let you intercept ctrl + break. Form the documentation:
import signal, os
def handler(signum, frame):
print 'Someone is trying to exit!', signum
signal.signal(signal.SIGBREAK, handler)

Python loop that always executes at least once? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
do-while loop in Python?
How do I write a loop in Python that will always be executed at least once, with the test being performed after the first iteration? (different to the 20 or so python examples of for and while loops I found through google and python docs)
while True:
#loop body
if (!condition): break
You could try:
def loop_body():
# implicitly return None, which is false-ish, at the end
while loop_body() or condition: pass
But realistically I think I would do it the other way. In practice, you don't really need it that often anyway. (Even less often than you think; try to refactor in other ways.)

Categories

Resources