View redirect-stdout-inside-loop.py
""" | |
Reason for publishing this Gist and the use case: | |
In many cases we use functions in libraries that print the variable we want instead of returning it. This Gist shows | |
how to get hold of the printed values from these functions and store in a variable. I found the solution in | |
couple of posts on different forums: | |
* https://stackoverflow.com/questions/1218933/can-i-redirect-the-stdout-in-python-into-some-sort-of-string-buffer | |
* https://wrongsideofmemphis.wordpress.com/2010/03/01/store-standard-output-on-a-variable-in-python/ | |
* https://groups.google.com/forum/#!topic/comp.lang.python/tkK6n1oVKhM | |
* https://bytes.com/topic/python/answers/849106-redirection-standard-output-python-command-python-variable | |
In addition to the trick demonstrated in these posts, I found a case where I would need to store multiple printouts |
View passing-last-index.py
""" | |
You have a function that takes an argument, this argument is the index of the last element you want to show from an | |
array. At some point you want found out that you want to use this function but grab all elements. Just pass None. | |
""" | |
def some_function(last_idx): | |
print(some_arr[:last_idx]) | |
some_arr = range(100) | |
last_idx = 5 | |
some_function(last_idx) | |
last_idx = None |