How do I make my python script communicate with my MSP430 launchpad? - python

I want to create a GUI in python and make it interact with my micro-controller board(MSP430G2).
Would like to know if there is any way to send/receive data between the two.

pip install python-msp430-tools
if __name__ == '__main__':
from msp430.util import hexdump
import time
mmc = MMC()
try:
mmc.connect()
print mmc.info()
#show what's there
hexdump((0, mmc.read(0)))
#speed test
t1 = time.time()
for n in range(10):
mmc.read(n)
t2 = time.time()
dt = t2 - t1
bytes = n * 512
print "%d bytes in %.2f seconds -> %.2f bytes/second" % (bytes, dt, bytes/dt)
finally:
mmc.release()
python-msp430-tools

Related

How to improve speed of slicing for interactive dataframe

I have a dataframe that is imported from csv/excel file. The file is a simulation data that sweeps variables. Different versions of the file sweep different variables. Sometimes, it sweeps variables a,c,e, other times, it sweeps variables b,c,d, .etc.
Currently, when slicing the interactive dataframe idf (idf = df.interactive()), I manually change the code, depending on the prior knowledge of what is swept.(slicing on all the columns in one step with "&" operator.)The execution time of slicing is 7.67 seconds in the example below. However, if I want to detect what variables are swept and slice the dataframe interactively, the execution speed increases a lot. (382 seconds.)
I wonder whether there is a syntax that enjoy both the fast speed and automatic detection of what variables are swept.
import pandas as pd
import numpy as np
import time
import panel as pn
pn.extension('tabulator')
import hvplot.pandas
import holoviews as hv
list_alphabet = ['a','b','c','d','e']
list_year = [2000,2001,2002,2003,2004,2005]
list_country = ['US','BE','NL','CN']
list_color = ['white','blue','red','green','black']
list_fruit = ['apple','banana','pear','peach']
list_price = ['high','medium','low']
list_currency = ['USD','EUR','CNY','CAD']
list_transport = ['walking','biking','car','bus','train','tram','plane']
list_age = [10,20,30,40,50,60,70]
dict_lst ={'alphabet':list_alphabet,'year':list_year,'country':list_country,'color':list_color,'fruit':list_fruit,'price':list_price,\
'currency':list_currency,'transport':list_transport,'age':list_age}
list_itertools = [dict_lst[x] for x in dict_lst.keys()]
df = pd.DataFrame(list(itertools.product(*list_itertools)), columns=[x for x in dict_lst.keys()])
df['value'] = df['year']+10*df['age']
if 'data' not in pn.state.cache.keys():
pn.state.cache['data'] = df.copy()
else:
df = pn.state.cache['data']
dict_selector = {}
for selector_name in lst_possible_swept_variables:
if selector_name in df.columns:
selector = pn.widgets.Select(name=selector_name, options=dict_lst[selector_name])
dict_selector[selector_name] = selector
idf = df.interactive()
# fast-execution but hard-coded
start_time = time.time()
df_pipeline = (
idf[
(idf.alphabet == dict_selector['alphabet']) & \
(idf.year == dict_selector['year']) & \
(idf.country == dict_selector['country']) & \
(idf.color == dict_selector['color']) & \
(idf.fruit == dict_selector['fruit']) & \
(idf.price == dict_selector['price']) & \
(idf.currency == dict_selector['currency']) & \
(idf.transport == dict_selector['transport']) & \
(idf.age == dict_selector['age']) \
].groupby(['alphabet','year','country','color','fruit','price','currency','transport','age'])
['value'].mean().to_frame().reset_index().sort_values(by='age').reset_index(drop=True)
)
print("--- %s seconds ---" % (time.time() - start_time))
## --- 7.60701847076416 seconds ---
# self-adjusting code but executed much slower
start_time = time.time()
idf_slice = idf
for key_name in dict_selector.keys():
idf_slice = idf_slice[idf_slice[key_name] == dict_selector[key_name]]
df_pipeline_slice = (idf_slice.groupby([x for x in dict_selector.keys()])['value'].mean().to_frame().reset_index().sort_values(by='age').reset_index(drop=True)
)
print("--- %s seconds ---" % (time.time() - start_time))
## --- 381.84749722480774 seconds ---

Tektronix MSO56 Oscilloscope: SEVERE Memory Error

I am collecting over 100k FastFrame images (100 frames, with 15k points each), with summary mode and collecting them via python pyvisa using ni-visa.
The error is as follows:
SEVERE
The system is low on memory. Some results may be incomplete. To remedy, reduce record length or remove one or more analytical features such as math, measurements, bus decode or search.
After that, I can disconnect, connect again, send commands which update the window, but cannot query anything.
I suspect it is something to do with a memory leak on MSO56 RAM, or communication queue.
Commands like *RST, CLEAR, LCS, and FACTORY do not fix the error.
import pyvisa
import time
if __name__ == '__main__':
## DEV Signal
rm = pyvisa.ResourceManager()
ll = rm.list_resources()
print('\n\n\n----------------------\nAvailable Resources\n----------------------')
for i in range(len(ll)):
print(F'Resource ID {i}: {ll[i]}')
#i = int(input(F"\n\nPlease select 'Resource ID' from above: "))
i=0;
inst = rm.open_resource(ll[i])
inst.timeout = 10000
reset = inst.write("*RST")
ind = inst.query("*IDN?")
print(F"\nResource {i}: {ind}")
inst.write('C1:OUTP ON')
inst.write('C2:OUTP ON')
# Wave signal
Ch = 1; # channel 1 || 2
wave_name = 'UT1'
Frq = 500000; #Hz
Peri = 1/Frq;# Length of waveform
print(F"Period: {Peri}")
# trigger on channel 2
inst.write(F'C2:BSWV WVTP,SQUARE,FRQ,{Frq},AMP,1,OFST,0,DUTY,1')
# signal on channel 1
inst.write(F'C1:BSWV WVTP,SQUARE,FRQ,{Frq},AMP,1,OFST,0,DUTY,10')
inst = []
scope_ip = '192.168.0.10';
rm = pyvisa.ResourceManager()
ll = rm.list_resources()
print(ll)
for l in ll:
if scope_ip in l:
vScope = rm.open_resource(l)
#vScope.clear()
#vScope.close()
vScope.timeout = 2000
## attempts to fix Memory Error
vScope.write_raw('FPANEL:PRESS RESTART')
vScope.write_raw('*PSC ON')
vScope.write_raw('*CLS')
vScope.write_raw('FACTORY\n')
vScope.write_raw('*RST')
vScope.write_raw('*CLEAR')
vScope.write_raw('*ESE 1')
vScope.write_raw('*SRE 0')
vScope.write_raw('DESE 1')
print('\nESR')
print(vScope.query('*ESR?'))
#print('\nEVMSG?')
#print(vScope.query('*EVMsg?'))
#print(vScope.query('*ESE ?'))
# Display Wave Forms
vScope.write_raw('DISPLAY:WAVEVIEW1:CH1:STATE 1')
vScope.write_raw('DISPLAY:WAVEVIEW1:CH2:STATE 1')
# Vertical Command Groups.
vScope.write_raw('CH1:Coupling DC')
vScope.write_raw('CH2:Coupling DC')
vScope.write_raw('CH1:SCALE .5') # *10 for the range
vScope.write_raw('CH2:SCALE .5')
vScope.write_raw('CH1:Position 0')
vScope.write_raw('CH2:Position 0')
vScope.write_raw('TRIGGER:A:TYPE EDGE')
vScope.write_raw('TRIGGER:A:EDGE:SOURCE CH2')
vScope.write_raw('TRIGger:A:LEVEL:CH2 0')
vScope.write_raw('TRIGger:A:EDGE:SLOpe RISE')
vScope.write_raw('Horizontal:Position 10')
vScope.write_raw('Horizontal:MODE MANUAL')
vScope.write_raw('Horizontal:Samplerate 25000000000')
vScope.write_raw('HORIZONTAL:MODE:RECORDLENGTH 25000')
vScope.write_raw('DATA:SOURCE CH1')
vScope.write_raw('ACQUIRE:STOPAFTER SEQUENCE')## triggers re-read
nframes = 100;
vScope.write_raw(F"HORIZONTAL:FASTFRAME:COUNT {nframes}")
if int(1):
vScope.write_raw(F"DATA:FRAMESTART {1+nframes}")
else:
vScope.write_raw('DATA:FRAMESTART 1')
vScope.write_raw(F"DATA:FRAMESTOP {1+nframes}")
vScope.write_raw('HORIZONTAL:FASTFRAME:STATE OFF')
vScope.write_raw('HORIZONTAL:FASTFRAME:STATE ON')
vScope.write_raw('HORIZONTAL:FASTFRAME:SUMFRAME:STATE ON')
vScope.write_raw(F"HORIZONTAL:FASTFRAME:SELECTED {1+nframes}")
t0 = time.time()
for i in range(1000000):
vScope.write_raw('ACQUIRE:STATE 1') ## triggers re-read
vScope.query('*opc?')
vScope.write_raw(b'WFMOUTPRE?')
wfmo = vScope.read_raw()
vScope.write_raw('CURVE?')
curve = vScope.read_raw()
if i%100 ==0:
print(F"Iteration {i}")
print(F"Time Delta: {time.time()-t0}")
t0=time.time()
Poor Solution.
Restarting the Scope with the power button works.
I should have added that in the question, but takes ~ 2 minutes and is not an elegant solution.

Does iowait time counted while psutil.cpu_percent are called?

I want to know if iowait time are counted in psutil.cpu_percent(), so write a code as below to test
#cat test.py
import os
import psutil
import time
p = psutil.Process(os.getpid())
start = time.time()
times_before_workload = p.cpu_times()
# this function return cpu_percent between two call. so we have to call it once before workload
percent_before_workload = p.cpu_percent()
# I call f open/close many times and read from the file
# hoping cpu will spent time on both user system and iowait
c = 1000
while c:
f = open('/tmp/big_text')
content = f.read(10240)
f.close()
c -= 1
end = time.time()
percent_after_workload = p.cpu_percent()
times_after_workload = p.cpu_times()
user_seconds = times_after_workload.user - times_before_workload.user
system_seconds = times_after_workload.system - times_before_workload.system
iowait_seconds = times_after_workload.iowait - times_before_workload.iowait
# if cpu percent == user_percent + system_percent + iowait_percent then it means yes. iowait are counted
print 'user_percent %s' % round(user_seconds / (end - start) * 100, 2)
print 'system_percent %s' % round(system_seconds / (end - start) * 100, 2)
print 'iowait_percent %s' % round(iowait_seconds / (end - start) * 100, 2)
print 'percent %s' % percent_after_workload
here is this output
#python test.py
user_percent 67.06
system_percent 67.06
iowait_percent 0.0
percent 134.8
The iowait is 0 so still can not verify. So question are
does iowait counted in cpu percent?
how to make iowait happen?(no zero)
No, iowait is not counted in cpu percent.
Run vmtouch to evict pages from memory at the start of each iteration of the loop.
You may need to install vmtouch:
apt update
apt install vmtouch
Run vmtouch in Python:
import subprocess
subprocess.run(['vmtouch', '-e', '/tmp/big_text'], stdout=subprocess.DEVNULL)
Reference: Why iowait of reading file is zero?

How to make progress bar for a function in python [duplicate]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I wrote a simple console app to upload and download files from an FTP server using the ftplib.
I would like the app to show some visualization of its download/upload progress for the user; each time a data chunk is downloaded, I would like it to provide a progress update, even if it's just a numeric representation like a percentage.
Importantly, I want to avoid erasing all the text that's been printed to the console in previous lines (i.e. I don't want to "clear" the entire terminal while printing the updated progress).
This seems a fairly common task – how can I go about making a progress bar or similar visualization that outputs to my console while preserving prior program output?
Python 3
A Simple, Customizable Progress Bar
Here's an aggregate of many of the answers below that I use regularly (no imports required).
Note: All code in this answer was created for Python 3; see end of answer to use this code with Python 2.
# Print iterations progress
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
"""
Call in a loop to create terminal progress bar
#params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optional : positive number of decimals in percent complete (Int)
length - Optional : character length of bar (Int)
fill - Optional : bar fill character (Str)
printEnd - Optional : end character (e.g. "\r", "\r\n") (Str)
"""
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filledLength = int(length * iteration // total)
bar = fill * filledLength + '-' * (length - filledLength)
print(f'\r{prefix} |{bar}| {percent}% {suffix}', end = printEnd)
# Print New Line on Complete
if iteration == total:
print()
Sample Usage
import time
# A List of Items
items = list(range(0, 57))
l = len(items)
# Initial call to print 0% progress
printProgressBar(0, l, prefix = 'Progress:', suffix = 'Complete', length = 50)
for i, item in enumerate(items):
# Do stuff...
time.sleep(0.1)
# Update Progress Bar
printProgressBar(i + 1, l, prefix = 'Progress:', suffix = 'Complete', length = 50)
Sample Output
Progress: |█████████████████████████████████████████████-----| 90.0% Complete
Update
There was discussion in the comments regarding an option that allows the progress bar to adjust dynamically to the terminal window width. While I don't recommend this, here's a gist that implements this feature (and notes the caveats).
Single-Call Version of The Above
A comment below referenced a nice answer posted in response to a similar question. I liked the ease of use it demonstrated and wrote a similar one, but opted to leave out the import of the sys module while adding in some of the features of the original printProgressBar function above.
Some benefits of this approach over the original function above include the elimination of an initial call to the function to print the progress bar at 0% and the use of enumerate becoming optional (i.e. it is no longer explicitly required to make the function work).
def progressBar(iterable, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
"""
Call in a loop to create terminal progress bar
#params:
iterable - Required : iterable object (Iterable)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optional : positive number of decimals in percent complete (Int)
length - Optional : character length of bar (Int)
fill - Optional : bar fill character (Str)
printEnd - Optional : end character (e.g. "\r", "\r\n") (Str)
"""
total = len(iterable)
# Progress Bar Printing Function
def printProgressBar (iteration):
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filledLength = int(length * iteration // total)
bar = fill * filledLength + '-' * (length - filledLength)
print(f'\r{prefix} |{bar}| {percent}% {suffix}', end = printEnd)
# Initial Call
printProgressBar(0)
# Update Progress Bar
for i, item in enumerate(iterable):
yield item
printProgressBar(i + 1)
# Print New Line on Complete
print()
Sample Usage
import time
# A List of Items
items = list(range(0, 57))
# A Nicer, Single-Call Usage
for item in progressBar(items, prefix = 'Progress:', suffix = 'Complete', length = 50):
# Do stuff...
time.sleep(0.1)
Sample Output
Progress: |█████████████████████████████████████████████-----| 90.0% Complete
Python 2
To use the above functions in Python 2, set the encoding to UTF-8 at the top of your script:
# -*- coding: utf-8 -*-
And replace the Python 3 string formatting in this line:
print(f'\r{prefix} |{bar}| {percent}% {suffix}', end = printEnd)
With Python 2 string formatting:
print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = printEnd)
Writing '\r' will move the cursor back to the beginning of the line.
This displays a percentage counter:
import time
import sys
for i in range(100):
time.sleep(1)
sys.stdout.write("\r%d%%" % i)
sys.stdout.flush()
tqdm: add a progress meter to your loops in a second:
>>> import time
>>> from tqdm import tqdm
>>> for i in tqdm(range(100)):
... time.sleep(1)
...
|###-------| 35/100 35% [elapsed: 00:35 left: 01:05, 1.00 iters/sec]
Write a \r to the console. That is a "carriage return" which causes all text after it to be echoed at the beginning of the line. Something like:
def update_progress(progress):
print '\r[{0}] {1}%'.format('#'*(progress/10), progress)
which will give you something like: [ ########## ] 100%
It is less than 10 lines of code.
The gist here: https://gist.github.com/vladignatyev/06860ec2040cb497f0f3
import sys
def progress(count, total, suffix=''):
bar_len = 60
filled_len = int(round(bar_len * count / float(total)))
percents = round(100.0 * count / float(total), 1)
bar = '=' * filled_len + '-' * (bar_len - filled_len)
sys.stdout.write('[%s] %s%s ...%s\r' % (bar, percents, '%', suffix))
sys.stdout.flush() # As suggested by Rom Ruben
Try the click library written by the Mozart of Python, Armin Ronacher.
$ pip install click # both 2 and 3 compatible
To create a simple progress bar:
import click
with click.progressbar(range(1000000)) as bar:
for i in bar:
pass
This is what it looks like:
# [###-------------------------------] 9% 00:01:14
Customize to your hearts content:
import click, sys
with click.progressbar(range(100000), file=sys.stderr, show_pos=True, width=70, bar_template='(_(_)=%(bar)sD(_(_| %(info)s', fill_char='=', empty_char=' ') as bar:
for i in bar:
pass
Custom look:
(_(_)===================================D(_(_| 100000/100000 00:00:02
There are even more options, see the API docs:
click.progressbar(iterable=None, length=None, label=None, show_eta=True, show_percent=None, show_pos=False, item_show_func=None, fill_char='#', empty_char='-', bar_template='%(label)s [%(bar)s] %(info)s', info_sep=' ', width=36, file=None, color=None)
I realize I'm late to the game, but here's a slightly Yum-style (Red Hat) one I wrote (not going for 100% accuracy here, but if you're using a progress bar for that level of accuracy, then you're WRONG anyway):
import sys
def cli_progress_test(end_val, bar_length=20):
for i in xrange(0, end_val):
percent = float(i) / end_val
hashes = '#' * int(round(percent * bar_length))
spaces = ' ' * (bar_length - len(hashes))
sys.stdout.write("\rPercent: [{0}] {1}%".format(hashes + spaces, int(round(percent * 100))))
sys.stdout.flush()
Should produce something looking like this:
Percent: [############## ] 69%
... where the brackets stay stationary and only the hashes increase.
This might work better as a decorator. For another day...
Check this library: clint
it has a lot of features including a progress bar:
from time import sleep
from random import random
from clint.textui import progress
if __name__ == '__main__':
for i in progress.bar(range(100)):
sleep(random() * 0.2)
for i in progress.dots(range(100)):
sleep(random() * 0.2)
this link provides a quick overview of its features
Here's a nice example of a progressbar written in Python: http://nadiana.com/animated-terminal-progress-bar-in-python
But if you want to write it yourself. You could use the curses module to make things easier :)
[edit]
Perhaps easier is not the word for curses. But if you want to create a full-blown cui than curses takes care of a lot of stuff for you.
[edit]
Since the old link is dead I have put up my own version of a Python Progressbar, get it here: https://github.com/WoLpH/python-progressbar
import time,sys
for i in range(100+1):
time.sleep(0.1)
sys.stdout.write(('='*i)+(''*(100-i))+("\r [ %d"%i+"% ] "))
sys.stdout.flush()
output
[ 29% ] ===================
Install tqdm.(pip install tqdm)
and use it as follows:
import time
from tqdm import tqdm
for i in tqdm(range(1000)):
time.sleep(0.01)
That's a 10 seconds progress bar that'll output something like this:
47%|██████████████████▊ | 470/1000 [00:04<00:05, 98.61it/s]
and, just to add to the pile, here's an object you can use:
Add the following to a new file progressbar.py
import sys
class ProgressBar(object):
CHAR_ON = '='
CHAR_OFF = ' '
def __init__(self, end=100, length=65):
self._end = end
self._length = length
self._chars = None
self._value = 0
#property
def value(self):
return self._value
#value.setter
def value(self, value):
self._value = max(0, min(value, self._end))
if self._chars != (c := int(self._length * (self._value / self._end))):
self._chars = c
sys.stdout.write("\r {:3n}% [{}{}]".format(
int((self._value / self._end) * 100.0),
self.CHAR_ON * int(self._chars),
self.CHAR_OFF * int(self._length - self._chars),
))
sys.stdout.flush()
def __enter__(self):
self.value = 0
return self
def __exit__(self, *args, **kwargs):
sys.stdout.write('\n')
Can be included in your program with:
import time
from progressbar import ProgressBar
count = 150
print("starting things:")
with ProgressBar(count) as bar:
for i in range(count + 1):
bar.value += 1
time.sleep(0.01)
print("done")
Results in:
starting things:
100% [=================================================================]
done
This may be "over the top", but is handy when used frequently.
Run this at the Python command line (not in any IDE or development environment):
>>> import threading
>>> for i in range(50+1):
... threading._sleep(0.5)
... print "\r%3d" % i, ('='*i)+('-'*(50-i)),
Works fine on my Windows system.
Try to install this package: pip install progressbar2 :
import time
import progressbar
for i in progressbar.progressbar(range(100)):
time.sleep(0.02)
progresssbar github: https://github.com/WoLpH/python-progressbar
http://code.activestate.com/recipes/168639-progress-bar-class/ (2002)
http://code.activestate.com/recipes/299207-console-text-progress-indicator-class/ (2004)
http://pypi.python.org/pypi/progressbar (2006)
And a lot of tutorials waiting to be googled.
based on the above answers and other similar questions about CLI progress bar, I think I got a general common answer to all of them. Check it at https://stackoverflow.com/a/15860757/2254146
In summary, the code is this:
import time, sys
# update_progress() : Displays or updates a console progress bar
## Accepts a float between 0 and 1. Any int will be converted to a float.
## A value under 0 represents a 'halt'.
## A value at 1 or bigger represents 100%
def update_progress(progress):
barLength = 10 # Modify this to change the length of the progress bar
status = ""
if isinstance(progress, int):
progress = float(progress)
if not isinstance(progress, float):
progress = 0
status = "error: progress var must be float\r\n"
if progress < 0:
progress = 0
status = "Halt...\r\n"
if progress >= 1:
progress = 1
status = "Done...\r\n"
block = int(round(barLength*progress))
text = "\rPercent: [{0}] {1}% {2}".format( "#"*block + "-"*(barLength-block), progress*100, status)
sys.stdout.write(text)
sys.stdout.flush()
Looks like
Percent: [##########] 99.0%
I am using progress from reddit. I like it because it can print progress for every item in one line, and it shouldn't erase printouts from the program.
Edit: fixed link
A very simple solution is to put this code into your loop:
Put this in the body (i.e. top) of your file:
import sys
Put this in the body of your loop:
sys.stdout.write("-") # prints a dash for each iteration of loop
sys.stdout.flush() # ensures bar is displayed incrementally
I recommend using tqdm - https://pypi.python.org/pypi/tqdm - which makes it simple to turn any iterable or process into a progress bar, and handles all messing about with terminals needed.
From the documentation: "tqdm can easily support callbacks/hooks and manual updates. Here’s an example with urllib"
import urllib
from tqdm import tqdm
def my_hook(t):
"""
Wraps tqdm instance. Don't forget to close() or __exit__()
the tqdm instance once you're done with it (easiest using `with` syntax).
Example
-------
>>> with tqdm(...) as t:
... reporthook = my_hook(t)
... urllib.urlretrieve(..., reporthook=reporthook)
"""
last_b = [0]
def inner(b=1, bsize=1, tsize=None):
"""
b : int, optional
Number of blocks just transferred [default: 1].
bsize : int, optional
Size of each block (in tqdm units) [default: 1].
tsize : int, optional
Total size (in tqdm units). If [default: None] remains unchanged.
"""
if tsize is not None:
t.total = tsize
t.update((b - last_b[0]) * bsize)
last_b[0] = b
return inner
eg_link = 'http://www.doc.ic.ac.uk/~cod11/matryoshka.zip'
with tqdm(unit='B', unit_scale=True, miniters=1,
desc=eg_link.split('/')[-1]) as t: # all optional kwargs
urllib.urlretrieve(eg_link, filename='/dev/null',
reporthook=my_hook(t), data=None)
import sys
def progresssbar():
for i in range(100):
time.sleep(1)
sys.stdout.write("%i\r" % i)
progressbar()
NOTE: if you run this in interactive interepter you get extra numbers printed out
lol i just wrote a whole thingy for this
heres the code keep in mind you cant use unicode when doing block ascii i use cp437
import os
import time
def load(left_side, right_side, length, time):
x = 0
y = ""
print "\r"
while x < length:
space = length - len(y)
space = " " * space
z = left + y + space + right
print "\r", z,
y += "█"
time.sleep(time)
x += 1
cls()
and you call it like so
print "loading something awesome"
load("|", "|", 10, .01)
so it looks like this
loading something awesome
|█████ |
With the great advices above I work out the progress bar.
However I would like to point out some shortcomings
Every time the progress bar is flushed, it will start on a new line
print('\r[{0}]{1}%'.format('#' * progress* 10, progress))
like this:
[] 0%
[#]10%
[##]20%
[###]30%
2.The square bracket ']' and the percent number on the right side shift right as the '###' get longer.
3. An error will occur if the expression 'progress / 10' can not return an integer.
And the following code will fix the problem above.
def update_progress(progress, total):
print('\r[{0:10}]{1:>2}%'.format('#' * int(progress * 10 /total), progress), end='')
For python 3:
def progress_bar(current_value, total):
increments = 50
percentual = ((current_value/ total) * 100)
i = int(percentual // (100 / increments ))
text = "\r[{0: <{1}}] {2}%".format('=' * i, increments, percentual)
print(text, end="\n" if percentual == 100 else "")
function from Greenstick for 2.7:
def printProgressBar (iteration, total, prefix = '', suffix = '',decimals = 1, length = 100, fill = '#'):
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filledLength = int(length * iteration // total)
bar = fill * filledLength + '-' * (length - filledLength)
print'\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix),
sys.stdout.flush()
# Print New Line on Complete
if iteration == total:
print()
Code for python terminal progress bar
import sys
import time
max_length = 5
at_length = max_length
empty = "-"
used = "%"
bar = empty * max_length
for i in range(0, max_length):
at_length -= 1
#setting empty and full spots
bar = used * i
bar = bar+empty * at_length
#\r is carriage return(sets cursor position in terminal to start of line)
#\0 character escape
sys.stdout.write("[{}]\0\r".format(bar))
sys.stdout.flush()
#do your stuff here instead of time.sleep
time.sleep(1)
sys.stdout.write("\n")
sys.stdout.flush()
The python module progressbar is a nice choice.
Here is my typical code:
import time
import progressbar
widgets = [
' ', progressbar.Percentage(),
' ', progressbar.SimpleProgress(format='(%(value_s)s of %(max_value_s)s)'),
' ', progressbar.Bar('>', fill='.'),
' ', progressbar.ETA(format_finished='- %(seconds)s -', format='ETA: %(seconds)s', ),
' - ', progressbar.DynamicMessage('loss'),
' - ', progressbar.DynamicMessage('error'),
' '
]
bar = progressbar.ProgressBar(redirect_stdout=True, widgets=widgets)
bar.start(100)
for i in range(100):
time.sleep(0.1)
bar.update(i + 1, loss=i / 100., error=i)
bar.finish()
i wrote a simple progressbar:
def bar(total, current, length=10, prefix="", filler="#", space=" ", oncomp="", border="[]", suffix=""):
if len(border) != 2:
print("parameter 'border' must include exactly 2 symbols!")
return None
print(prefix + border[0] + (filler * int(current / total * length) +
(space * (length - int(current / total * length)))) + border[1], suffix, "\r", end="")
if total == current:
if oncomp:
print(prefix + border[0] + space * int(((length - len(oncomp)) / 2)) +
oncomp + space * int(((length - len(oncomp)) / 2)) + border[1], suffix)
if not oncomp:
print(prefix + border[0] + (filler * int(current / total * length) +
(space * (length - int(current / total * length)))) + border[1], suffix)
as you can see, it have: length of bar, prefix and suffix, filler, space, text in bar on 100%(oncomp) and borders
here an example:
from time import sleep, time
start_time = time()
for i in range(10):
pref = str((i+1) * 10) + "% "
complete_text = "done in %s sec" % str(round(time() - start_time))
sleep(1)
bar(10, i + 1, length=20, prefix=pref, oncomp=complete_text)
out in progress:
30% [###### ]
out on complete:
100% [ done in 9 sec ]
Putting together some of the ideas I found here, and adding estimated time left:
import datetime, sys
start = datetime.datetime.now()
def print_progress_bar (iteration, total):
process_duration_samples = []
average_samples = 5
end = datetime.datetime.now()
process_duration = end - start
if len(process_duration_samples) == 0:
process_duration_samples = [process_duration] * average_samples
process_duration_samples = process_duration_samples[1:average_samples-1] + [process_duration]
average_process_duration = sum(process_duration_samples, datetime.timedelta()) / len(process_duration_samples)
remaining_steps = total - iteration
remaining_time_estimation = remaining_steps * average_process_duration
bars_string = int(float(iteration) / float(total) * 20.)
sys.stdout.write(
"\r[%-20s] %d%% (%s/%s) Estimated time left: %s" % (
'='*bars_string, float(iteration) / float(total) * 100,
iteration,
total,
remaining_time_estimation
)
)
sys.stdout.flush()
if iteration + 1 == total:
print
# Sample usage
for i in range(0,300):
print_progress_bar(i, 300)
Well here is code that works and I tested it before posting:
import sys
def prg(prog, fillchar, emptchar):
fillt = 0
emptt = 20
if prog < 100 and prog > 0:
prog2 = prog/5
fillt = fillt + prog2
emptt = emptt - prog2
sys.stdout.write("\r[" + str(fillchar)*fillt + str(emptchar)*emptt + "]" + str(prog) + "%")
sys.stdout.flush()
elif prog >= 100:
prog = 100
prog2 = prog/5
fillt = fillt + prog2
emptt = emptt - prog2
sys.stdout.write("\r[" + str(fillchar)*fillt + str(emptchar)*emptt + "]" + str(prog) + "%" + "\nDone!")
sys.stdout.flush()
elif prog < 0:
prog = 0
prog2 = prog/5
fillt = fillt + prog2
emptt = emptt - prog2
sys.stdout.write("\r[" + str(fillchar)*fillt + str(emptchar)*emptt + "]" + str(prog) + "%" + "\nHalted!")
sys.stdout.flush()
Pros:
20 character bar (1 character for every 5 (number wise))
Custom fill characters
Custom empty characters
Halt (any number below 0)
Done (100 and any number above 100)
Progress count (0-100 (below and above used for special functions))
Percentage number next to bar, and it's a single line
Cons:
Supports integers only (It can be modified to support them though, by making the division an integer division, so just change prog2 = prog/5 to prog2 = int(prog/5))
Here's my Python 3 solution:
import time
for i in range(100):
time.sleep(1)
s = "{}% Complete".format(i)
print(s,end=len(s) * '\b')
'\b' is a backslash, for each character in your string.
This does not work within the Windows cmd window.

Get upload/download kbps speed

I'm using the library called psutil to get system/network stats, but I can only get the total uploaded/downloaded bytes on my script.
What would be the way to natively get the network speed using Python?
If you need to know the transfer rate immediately, you should create a thread that does the calculations continuously. I'm not an expert on the subject, but I tried writing a simple program that does what you need:
import threading
import time
from collections import deque
import psutil
def calc_ul_dl(rate, dt=3, interface="WiFi"):
t0 = time.time()
counter = psutil.net_io_counters(pernic=True)[interface]
tot = (counter.bytes_sent, counter.bytes_recv)
while True:
last_tot = tot
time.sleep(dt)
counter = psutil.net_io_counters(pernic=True)[interface]
t1 = time.time()
tot = (counter.bytes_sent, counter.bytes_recv)
ul, dl = [
(now - last) / (t1 - t0) / 1000.0
for now, last in zip(tot, last_tot)
]
rate.append((ul, dl))
t0 = time.time()
def print_rate(rate):
try:
print("UL: {0:.0f} kB/s / DL: {1:.0f} kB/s".format(*rate[-1]))
except IndexError:
"UL: - kB/s/ DL: - kB/s"
# Create the ul/dl thread and a deque of length 1 to hold the ul/dl- values
transfer_rate = deque(maxlen=1)
t = threading.Thread(target=calc_ul_dl, args=(transfer_rate,))
# The program will exit if there are only daemonic threads left.
t.daemon = True
t.start()
# The rest of your program, emulated by me using a while True loop
while True:
print_rate(transfer_rate)
time.sleep(5)
Here you should set the dt argument to whatever seams reasonable for you. I tried using 3 seconds, and this is my output while runnning an online speedtest:
UL: 2 kB/s / DL: 8 kB/s
UL: 3 kB/s / DL: 45 kB/s
UL: 24 kB/s / DL: 1306 kB/s
UL: 79 kB/s / DL: 4 kB/s
UL: 121 kB/s / DL: 3 kB/s
UL: 116 kB/s / DL: 4 kB/s
UL: 0 kB/s / DL: 0 kB/s
The values seems reasonable since my result from the speedtest were DL: 1258 kB/s and UL: 111 kB/s.
The answer provided by Steinar Lima is correct.
But it can be done without threading also:
import time
import psutil
import os
count = 0
qry = ""
ul = 0.00
dl = 0.00
t0 = time.time()
upload = psutil.net_io_counters(pernic=True)["Wireless Network Connection"][0]
download = psutil.net_io_counters(pernic=True)["Wireless Network Connection"][1]
up_down = (upload, download)
while True:
last_up_down = up_down
upload = psutil.net_io_counters(pernic=True)["Wireless Network Connection"][0]
download = psutil.net_io_counters(pernic=True)["Wireless Network Connection"][1]
t1 = time.time()
up_down = (upload, download)
try:
ul, dl = [
(now - last) / (t1 - t0) / 1024.0
for now, last in zip(up_down, last_up_down)
]
t0 = time.time()
except:
pass
if dl > 0.1 or ul >= 0.1:
time.sleep(0.75)
os.system("cls")
print("UL: {:0.2f} kB/s \n".format(ul) + "DL: {:0.2f} kB/s".format(dl))
v = input()
Simple and easy ;)
I added an LCD mod for this code if you want to test it on a raspberry pi but you need to add the psutil and the lcddriver to your project code!!!!
import time
import psutil
import os
import lcddriver
count=0
qry=''
ul=0.00
dl=0.00
t0 = time.time()
upload=psutil.net_io_counters(pernic=True)['wlan0'][0]
download=psutil.net_io_counters(pernic=True)['wlan0'][1]
up_down=(upload,download)
display = lcddriver.lcd()
while True:
last_up_down = up_down
upload=psutil.net_io_counters(pernic=True)['wlan0'][0]
download=psutil.net_io_counters(pernic=True)['wlan0'][1]
t1 = time.time()
up_down = (upload,download)
try:
ul, dl = [(now - last) / (t1 - t0) / 1024.0
for now,last in zip(up_down, last_up_down)]
t0 = time.time()
#display.lcd_display_string(str(datetime.datetime.now().time()), 1)
except:
pass
if dl>0.1 or ul>=0.1:
time.sleep(0.75)
os.system('cls')
print('UL: {:0.2f} kB/s \n'.format(ul)+'DL:{:0.2f} kB/s'.format(dl))
display.lcd_display_string(str('DL:{:0.2f} KB/s '.format(dl)), 1)
display.lcd_display_string(str('UL:{:0.2f} KB/s '.format(ul)), 2)
# if KeyboardInterrupt: # If there is a KeyboardInterrupt (when you press ctrl+c), exit the program and cleanup
# print("Cleaning up!")
# display.lcd_clear()
v=input()
The (effective) network speed is simply bytes transferred in a given time interval, divided by the length of the interval. Obviously there are different ways to aggregate / average the times and they give you different "measures" ... but it all basically boils down to division.
Another and more simple solution (without threading and queues although still based on #Steinar Lima) and for more recent python:
import time
import psutil
def on_calculate_speed(self, interface):
dt = 1 # I find that dt = 1 is good enough
t0 = time.time()
try:
counter = psutil.net_io_counters(pernic=True)[interface]
except KeyError:
return []
tot = (counter.bytes_sent, counter.bytes_recv)
while True:
last_tot = tot
time.sleep(dt)
try:
counter = psutil.net_io_counters(pernic=True)[interface]
except KeyError:
break
t1 = time.time()
tot = (counter.bytes_sent, counter.bytes_recv)
ul, dl = [
(now - last) / (t1 - t0) / 1000.0
for now, last
in zip(tot, last_tot)
]
return [int(ul), int(dl)]
t0 = time.time()
while SomeCondition:
# "wlp2s0" is usually the default wifi interface for linux, but you
# could use any other interface that you want/have.
interface = "wlp2s0"
result_speed = on_calculate_speed(interface)
if len(result_speed) < 1:
print("Upload: - kB/s/ Download: - kB/s")
else:
ul, dl = result_speed[0], result_speed[1]
print("Upload: {} kB/s / Download: {} kB/s".format(ul, dl))
Or you could also fetch the default interface with pyroute2:
while SomeCondition:
ip = IPDB()
interface = ip.interfaces[ip.routes['default']['oif']]["ifname"]
result_speed = on_calculate_speed(interface)
if len(result_speed) < 1:
print("Upload: - kB/s/ Download: - kB/s")
else:
ul, dl = result_speed[0], result_speed[1]
print("Upload: {} kB/s / Download: {} kB/s".format(ul, dl))
ip.release()
i found this tread, and dont have any idea from python, i jst copy and paste codes, and now need a little help, this script, i have jst show the total of bytes send/recived, can modify to show the actual speed?
def network(iface):
stat = psutil.net_io_counters(pernic=True)[iface]
return "%s: Tx%s, Rx%s" % \
(iface, bytes2human(stat.bytes_sent), bytes2human(stat.bytes_recv))
def stats(device):
# use custom font
font_path = str(Path(__file__).resolve().parent.joinpath('fonts', 'C&C Red Alert [INET].ttf'))
font_path2 = str(Path(__file__).resolve().parent.joinpath('fonts', 'Stockholm.ttf'))
font2 = ImageFont.truetype(font_path, 12)
font3 = ImageFont.truetype(font_path2, 11)
with canvas(device) as draw:
draw.text((0, 0), cpu_usage(), font=font2, fill="white")
if device.height >= 32:
draw.text((0, 14), mem_usage(), font=font2, fill="white")
if device.height >= 64:
draw.text((0, 26), "IP: " + getIP("eth0"), font=font2, fill=255)
try:
draw.text((0, 38), network('eth0'), font=font2, fill="white")
except KeyError:
# no wifi enabled/available
pass
The code
# pip install speedtest-cli
import speedtest
speed_test = speedtest.Speedtest()
def bytes_to_mb(bytes):
KB = 1024 # One Kilobyte is 1024 bytes
MB = KB * 1024 # One MB is 1024 KB
return int(bytes/MB)
download_speed = bytes_to_mb(speed_test.download())
print("Your Download speed is", download_speed, "MB")
upload_speed = bytes_to_mb(speed_test.upload())
print("Your Upload speed is", upload_speed, "MB")
The first answer in interface should be change to desired network adapter. To see the name in ubuntu you can use ifconfig, then change interface='wifi' to the device name.
a little change to formatting in python3
def print_rate(rate):
try:
print(('UL: {0:.0f} kB/s / DL: {1:.0f} kB/s').format(*rate[-1]))
except IndexError:
'UL: - kB/s/ DL: - kB/s'

Categories