Update text in the pycharm console - python

I'm trying to make a script to calculate pi, but by increasing the steps in the main for loop, it drastically increases in the time it takes to calculate. Sometimes its hard to tell if its doing anything at all. So to fix this I put the following in the main for loop:
# prints the progress percentage (or pp)
pp = (i/rolls)*100
print(pp.__round__(pp_decimals))
rolls in the total number of times the loop will execute.
But this presents a new problem, this ends up printing ALOT of text, and all the print calls end up lagging my pc as well as clogging up the terminal. So my question is, how can I edit the text or delete previous text in order to clear up the output?

It is best to approach your problem in a different way. I assume that i is loop counter so you can print progress percentage in every t times instead clearing the output:
# prints the progress percentage (or pp)
if i % 10 == 0: # t is 10 in this example
pp = (i/rolls)*100
print(pp.__round__(pp_decimals))

Related

collecting data from running program

I am working on a problem where i should collect data from running program numerous times. For example, every time the program finishes commands, it give certain value t, which is different every time run it. My task is to collect t from N runs of the program. t is going to be different every run. here is the program:
import random
th=0
t=0
tr=0
result=[]
for i in range(7):
i=random.randint(0,1)
result.append(i)
print(result)
a=0
b=len(result)-1
while th<50:
j=random.randint(a,b)
i=j-1
k=j+1
if k<b
k=0
if result[i]==result[k]:
if result[j]!=result[i]:
result[j]==result[i]
th=0
t+=1
else:
th+=1
t+=1
else:
th+=1
t+=1
tr= t-th
print(tr)
print (result)
In this program every run gives you new result. In this generated array there will be obviously every time different arrangement of 0 and 1 and therefore, different t. So resulting t, tr, will be ofcourse different.
I don't know wheter i should do it in new window, or there is a certain function that can do this. Also, if this question is to easy, and there is literature for it, please write what is the name of this kind of problem. thanks :)
btw, im working in python 3.6
See how to make one Python script launch another: you can write a Python script to run the other script and gather the output. You can receive the output as return value from a function call, and tally it just as you would from any function.
Note that your "running program" and your master script need to agree on the form of the information returned: know the data types you're receiving. If you're in doubt, start by having your master script print out what it receives, and the type of each returned value.

Does using print() too much cause it to fail?

TL;DR:
The print() result is not updating in a Windows Console. Executes fine in IDLE. Program is executing even though Windows Console is not updating.
Background
I have a file, test.py that contains:
Edit: Included the conditions that I used to see if the Console was updating. Eventually the series of X values never prints again in Console and the Console never scrolls back up (as it normally does when output is being generated at the bottom).
count = 0
while True:
print ("True")
count += 1
if count == 10:
print ("XXXXXXXXX")
count = 0
When I run this in cmd.exe it obviously prints a very large number of True.
However, after about 25 seconds of running, it stops printing any more, though the program is still running and can be seen in the Task Manager.
I have a program with some progress indicators that end up stay at say 50% even though they are moving well beyond 50% simply because print() is not showing in the Console output.
Edit: The true use case problem.
The above code was just a test file to see if printing in Console stopped in all programs, not the one I was running. In practice, my program prints to Console and looks like:
line [10] >> Progress 05%
Where line [10] isn't real but I merely typed here to show you that print() sends to that line in the Console window. As my program continues it increments:
line [10] >> Progress 06%
line [10] >> Progress 11%
.
.
.
line [10] >> Progress 50%
Each time line [10] is overwritten. I use ANSI escape characters and colorama to move the Console cursor accordingly:
print('\x1b[1000D\x1b[1A')
This moves the cursor 1000 columns left and 1 row up (so the start of the previous line).
Something is happening where the print("Progress " + prog + "%") is not showing up anymore in Console because eventually the next bit of Python gets executed:
line [11] >> Program Complete...
I verified the resultants which get put into a folder. So the program continued to run while the Console did not update.
Edit: Here is the script running the updates to the stdout.
def check_queue(q, dates, dct):
out = 0
height = 0
# print the initial columns and rows of output
# each cell has a unique id
# so they are stored in a dictionary
# then I convert to list to print by subscripting
for x in range(0, len(list(dct.values())), 3):
print("\t\t".join(list(dct.values())[x:x+3]))
height +=1 # to determine where the top is for cursor
while True:
if out != (len(dates) * 2):
try:
status = q.get_nowait()
dct[status[1]] = status[2]
print('\x1b[1000D\x1b[' + str(height + 1) + 'A')
# since there was a message that means a value was updated
for x in range(0, len(list(dct.values())), 3):
print("\t\t".join(list(dct.values())[x:x+3]))
if status[0] == 'S' or 'C' or 'F':
out += 1
except queue.Empty:
pass
else:
break
In short, I pass a message to the queue from a thread. I then update a dictionary that holds unique cell IDs. I update the value, move the cursor in Console to the upper left position of the printed list, and print over it.
Question:
When using stdout, is there a limit to how many times you can print to it in a period of time?
That may well be an illusion (maybe because there's a maximum limit of lines in the console and new ones just replace the first ones then).
There's definetly no limit how much you can print. You could verify this with something that changes each iteration, for example a loop that counts the number of iterations:
import itertools
for i in itertools.count():
print(i, "True")
I cannot reproduce the problem in Windows 10 using 64-bit Python 3.6.2 and colorama 0.3.9. Here's the simple example that I tested:
import colorama
colorama.init()
def test(M=10, N=1000):
for x in range(M):
print('spam')
for n in range(N):
print('\x1b[1000D\x1b[' + str(M + 1) + 'A')
for m in range(M):
print('spam', m, n)
Each pass successfully overwrites the previous lines. Here's the final output from looping N (1000) times:
>>> test()
spam 0 999
spam 1 999
spam 2 999
spam 3 999
spam 4 999
spam 5 999
spam 6 999
spam 7 999
spam 8 999
spam 9 999
If this example fails for you, please update your question and include the versions of Windows, Python, and colorama that you're testing.
Sounds like it might be a system limitation, not a Python process issue? I've never run across a 'hang' related to print statements (or any built-in function), however you may want to look at mapping performance and memory usage:
High Memory Usage Using Python Multiprocessing
As far as how many times you can print in a period of time, that is almost exclusively based on the speed the system executes the code. You could run some benchmark tests (execution time / number of executions) across several platforms to test performance with specific system specs, but I'd say the likely cause of your issue is system / environment related.

Terminal output turns black

Short version: I have a program that prints to the terminal successive integer numbers in an infinite loop. At some point, the terminal became black, and no output is visible, but I can still execute commands.
Details:
I read this answer in PCG and wanted to try it in Python. Here it is:
#!/bin/python2
class Dier(object):
def __init__(self):
global ct
ct += 1
print ct
def __del__(self):
Dier()
ct = 0
Dier()
This program loops indefinitely, printing the number of iterations on each step. Left overnight (we get to the tenths of millions in a matter of minutes) executed from an Ubuntu gnome terminal, the terminall just shows black. The program is still running, and new lines appear, but nothing is visible. I killed the program, but the terminal, including the command prompt, is black. I can input commands, and they work, but no output is visible.
Why is this happening?
Some information I provided in the comments:
The memory used by the program (reported by top) remains constant and low.
I can print absurdly large numbers to the terminal without getting this behaviour. The largest number I have printed has 10^10^6 digits (of course, the terminal has forgotten the beginning of it, and only shows the last digits, but its log10 is 1246124). My program couldn't have gone that far, that would take millions of times the age of the universe.
On an added note, if I try to print something ever bigger than that, it just seems to freeze, using the CPU but without any output (while the original output was there, but invisible).
Seems like the output is being buffered. You should try and change the print to
print ct, "\n"
or
print ct
sys.stdout.flush()
alternatively you can tell python to not buffer the output by calling it with -u parameter (see https://docs.python.org/2/using/cmdline.html#cmdoption-u) or setting PYTHONUNBUFFERED=1 env variable (see https://docs.python.org/2/using/cmdline.html#envvar-PYTHONUNBUFFERED)

Python Test sensors, then run them all again until keypress

I`m making a python program for my small greenhouse to test different condition.
What I need it to do is: when the program ends, wait 5 min then run all the tests again.
This is my first ever full python program, so if you can keep the answer in the low learing curve area it would be greatly appriciated.
example:
temp=probe1
humidity=probe2
CO2=probe3
if temp==25:
print ("25)"
if humidity==90:
print ("90")
if CO2==1000
print ("1000")
import time
time.sleep (300)
start again from top until keypress
You can put what you have now in a while True loop to achieve the desired result. This will run forever, making measurements every 5 minutes, until you interrupt the program by pressing Ctrl-C.
import time
while True:
temp=probe1
humidity=probe2
CO2=probe3
if temp==25:
print ("25")
if humidity==90:
print ("90")
if CO2==1000
print ("1000")
time.sleep (300)
However, I'm left wondering how likely it is that your sensors give precisely the values you check for. You might go without any output for hours or even longer, depending on the precision of the sensor values. You might want to check the rounded sensor values, e.g. if round(temp) == 25.
Or maybe you want to know when temp is 25 or higher, which you can check with if temp >= 25.
Another possibility would be to always print the sensor data, and print an extra warning in case the values are higher than some threshold, e.g.:
import time
while True:
temp=probe1
humidity=probe2
CO2=probe3
print("Temp:", temp, "degrees")
if temp>=25:
print (" Too hot!")
print("Humidity:", humidity, "%")
if humidity>=90:
print (" Too humid!")
print("CO2:", CO2, "units")
if CO2>=1000
print (" Too much CO2!")
time.sleep (300)

progress of loop indicator [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python Progress Bar
I am running a for loop 10,000 times,
but inside the loop there are a lot of calculations going on.
I would like to print out a progress message to the console informing me how far along in the loop the program is how much longer I might have to wait.
the basic loop is
n = 10000
for i in range(n):
do_stuff_method()
if(i%100 == 0):
print (float(i)/n)*100,
This prints out a percentage message on the same line, but the problem is that the next thing that I print out is also printed out on the same screen. That, and since there are 99 prinouts, the console gets pretty wide and there is a lot of scrolling across.
What I would really like is for the console to print out the current % done, and an estimated time to finsih on the one line replace that which had been previously printed, so there doesn't have to be a lot scrolling.
Can this be done?
Cheers,
Davy
In your case you can do it simply by changing your print line to be:
print "\r{0}".format((float(i)/n)*100),
Or you can try it like this instead of print:
sys.stdout.write("\r{0}".format((float(i)/n)*100))
sys.stdout.flush()

Categories

Resources