Categories
Python Answers

How to generate random integers between 0 and 9 with Python?

Sometimes, we want to generate random integers between 0 and 9 with Python.

In this article, we’ll look at how to generate random integers between 0 and 9 with Python.

How to generate random integers between 0 and 9 with Python?

To generate random integers between 0 and 9 with Python, we can use the randrange function from the random module.

For instance, we write:

from random import randrange

print(randrange(10))

We call randrange with 10 to generate a random number between 0 and 9 and return it.

Conclusion

To generate random integers between 0 and 9 with Python, we can use the randrange function from the random module.

Categories
Python Answers

How to get live output from the subprocess command with Python?

Sometimes, we want to get live output from the subprocess command with Python.

In this article, we’ll look at how to get live output from the subprocess command with Python.

How to get live output from the subprocess command with Python?

To get live output from the subprocess command with Python, we can open a file with open and write to it with write.

And sys.stdout.buffer.write will write the output to the screen.

For instance, we write:

import subprocess
import sys
with open('test.log', 'wb') as f:
    process = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE)
    for c in iter(lambda: process.stdout.read(1), b''):
        sys.stdout.buffer.write(c)
        f.write(c)

We open the file with open.

Then we call subprocess.POpen with the command and argument in a list and set stdout to subprocess.PIPE.

Next, we loop through the iterator that we get from call iter with process.stdout.read(1) to read the live output and loop through them.

In the loop body, we call sys.stdout.buffer.write to write the output to the screen and f.write to write the output to test.log

Therefore, we get something like:

total 20
-rw-r--r-- 1 runner runner   19 Oct 22 23:52 foo.csv
-rw-r--r-- 1 runner runner  242 Oct 23 16:45 main.py
-rw-r--r-- 1 runner runner    4 Oct 23 16:24 out.txt
-rw-r--r-- 1 runner runner 1473 Oct 23 16:28 poetry.lock
-rw-r--r-- 1 runner runner  312 Oct 23 16:28 pyproject.toml
-rw-r--r-- 1 runner runner    0 Oct 23 16:52 test.log

written to the screen and to the file.

Conclusion

To get live output from the subprocess command with Python, we can open a file with open and write to it with write.

And sys.stdout.buffer.write will write the output to the screen.

Categories
Python Answers

How to grab visible webpage text with BeautifulSoup?

Sometimes, we want to grab visible webpage text with BeautifulSoup.

In this article, we’ll look at how to grab visible webpage text with BeautifulSoup.

How to grab visible webpage text with BeautifulSoup?

To grab visible webpage text with BeautifulSoup, we can call filter when we’re grabbing the webpage content.

For instance, we write:

from bs4 import BeautifulSoup
from bs4.element import Comment
import urllib.request


def tag_visible(element):
    if element.parent.name in [
            'style', 'script', 'head', 'title', 'meta', '[document]'
    ]:
        return False
    if isinstance(element, Comment):
        return False
    return True


def text_from_html(body):
    soup = BeautifulSoup(body, 'html.parser')
    texts = soup.findAll(text=True)
    visible_texts = filter(tag_visible, texts)
    return u" ".join(t.strip() for t in visible_texts)


html = urllib.request.urlopen('https://yahoo.com').read()
print(text_from_html(html))

We have the tag_visible function that checks for tags for invisible elements by checking the element.parent.name for the tags that aren’t displayed.

We return True for the visible tags and False otherwise.

Then we define the text_from_html function to grab the text.

We use the BeautifulSoup constructor with body to get the content.

Then we call soup.findAll with text set to True to get all the nodes with text content.

And then we call filter with tag_visible and texts to get the visible nodes.

And finally, we call join to join all the results together.

We then get the HTML with urllib.request.urlopen and call text_from_html with the returned HTML.

Conclusion

To grab visible webpage text with BeautifulSoup, we can call filter when we’re grabbing the webpage content.

Categories
Python Answers

How to redirect print output to a file with Python?

Sometimes, we want to redirect print output to a file with Python.

In this article, we’ll look at how to redirect print output to a file with Python.

How to redirect print output to a file with Python?

To redirect print output to a file with Python, we can set the file argument of print.

For instance, we write:

with open('out.txt', 'w') as f:
    print('foo', file=f)

We call open with the path of the file to write to and 'w' permission to let us write to the file.

Then we set the file parameter to f when we call print.

Now 'foo' will be written to out.txt.

The file will be closed automatically when writing is done since we used with when we open the file.

Conclusion

To redirect print output to a file with Python, we can set the file argument of print.

Categories
Python Answers

How to convert seconds to hours, minutes and seconds with Python?

Sometimes, we want to convert seconds to hours, minutes and seconds with Python.

In this article, we’ll look at how to convert seconds to hours, minutes and seconds with Python.

How to convert seconds to hours, minutes and seconds with Python?

To convert seconds to hours, minutes and seconds with Python, we can use the datetime module.

For instance, we write:

import datetime

t = str(datetime.timedelta(seconds=10000))
print(t)

We call datetime.timedelta with the seconds set.

Then we call str on the returned object to get the seconds in hours, minutes, and seconds format.

Therefore, t is '2:46:40'.

Conclusion

To convert seconds to hours, minutes and seconds with Python, we can use the datetime module.