Categories
Python Answers

How to manually raise or throw an exception in Python?

Sometimes, we want to manually raise or throw an exception in Python.

In this article, we’ll look at how to manually raise or throw an exception in Python.

How to manually raise or throw an exception in Python?

To manually raise or throw an exception in Python, we can use the raise keyword.

For instance, we write:

try:
    raise ValueError('Represents a hidden bug, do not catch this')
    raise Exception('This is the exception you expect to handle')
except Exception as error:
    print(repr(error))

We use raise with ValueError to raise ValueError with a message.

Then we use the except clause to catch the Exception error, which is the parent class of all exceptions.

So the print call will print ValueError('Represents a hidden bug, do not catch this').

And the Exception exception is never raised.

Conclusion

To manually raise or throw an exception in Python, we can use the raise keyword.

Categories
Python Answers

How to process escape sequences in a string in Python?

Sometimes, we want to process escape sequences in a string in Python.

In this article, we’ll look at how to process escape sequences in a string in Python.

How to process escape sequences in a string in Python?

To process escape sequences in a string in Python, we can use the Python byte’s decode method.

For instance, we write:

s = "spam\\neggs"
decoded_string = bytes(s, "utf-8").decode("unicode_escape")
print(decoded_string)

We call bytes with string s and 'utf-8' encoding.

Then we call decode with 'unicode_escape' to decode the escape characters.

Therefore, decoded_string is:

spam
eggs

Conclusion

To process escape sequences in a string in Python, we can use the Python byte’s decode method.

Categories
Python Answers

How to read subprocess stdout line by line in Python?

Sometimes, we want to read subprocess stdout line by line in Python?

In this article, we’ll look at how to read subprocess stdout line by line in Python?

How to read subprocess stdout line by line in Python?

To read subprocess stdout line by line in Python, we can call stdout.readline on the returned process object.

For instance, we write:

import subprocess

proc = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE)
while True:
    line = proc.stdout.readline()
    if not line:
        break
    print(line.rstrip())

We call subprocess.Popen with a list of strings with the command and command line arguments.

Then we set stdout to subprocess.PIPE to return the output.

Next, we call proc.stdout.readline to return the next line of the stdout output in the while loop.

If line is None, then we stop the loop.

Otherwise, we print the line.

Therefore, we get text like:

b'total 64'
b'-rw-r--r-- 1 runner runner   183 Oct 20 01:10 main.py'
b'-rw-r--r-- 1 runner runner 14924 Oct 19 23:40 poetry.lock'
b'drwxr-xr-x 1 runner runner   126 Oct 19 23:17 __pycache__'
b'-rw-r--r-- 1 runner runner   319 Oct 19 23:39 pyproject.toml'
b'-rw-r--r-- 1 runner runner 12543 Oct 20 00:16 somepic.png'
b'-rw-r--r-- 1 runner runner   197 Oct 19 23:21 strings.json'
b'-rw------- 1 runner runner 18453 Oct 20 00:16 test1.png'

on the screen.

Conclusion

To read subprocess stdout line by line in Python, we can call stdout.readline on the returned process object.

Categories
Python Answers

How to change one character in a string with Python?

Sometimes, we want to change one character in a string with Python.

In this article, we’ll look at how to change one character in a string with Python.

How to change one character in a string with Python?

To change one character in a string with Python, we can convert the string to a list with list.

Then we change the character at the given list index.

And then we convert the list back to a string with join.

For instance, we write:

text = 'abcdefg'
new = list(text)
new[6] = 'W'
s = ''.join(new)
print(s)

We call list with text to convert text to the new list.

Then we set the character at index 6 of the list to 'W'.

Next, we call ''.join with new to convert new back to a string and assign the returned string to s.

Therefore, s is 'abcdefW'.

Conclusion

To change one character in a string with Python, we can convert the string to a list with list.

Then we change the character at the given list index.

And then we convert the list back to a string with join.

Categories
Python Answers

How to resize an image using PIL and maintain its aspect ratio with Python?

Sometimes, we want to resize an image using PIL and maintain its aspect ratio with Python.

In this article, we’ll look at how to resize an image using PIL and maintain its aspect ratio with Python.

How to resize an image using PIL and maintain its aspect ratio with Python?

To resize an image using PIL and maintain its aspect ratio with Python, we can open the image with Image.open.

Then we calculate the new width and height to scale the image to according to the new width.

And then we resize the image with the resize method and save the new image with the save method.

For instance, we write:

from PIL import Image

basewidth = 300
img = Image.open('test1.png')
wpercent = (basewidth / float(img.size[0]))
hsize = int((float(img.size[1]) * float(wpercent)))
img = img.resize((basewidth, hsize), Image.ANTIALIAS)
img.save('somepic.png')

We set the new width with:

basewidth = 300

Then we open the image with:

img = Image.open('test1.png')

Next, we compute the scale factor with:

wpercent = (basewidth / float(img.size[0]))

Then we get the height of the image with:

hsize = int((float(img.size[1]) * float(wpercent)))

Next, we write:

img = img.resize((basewidth, hsize), Image.ANTIALIAS)

to resize the image.

We use Image.ANTIALIAS to apply image anti-aliasing while resizing.

And finally, we call image.save with the file path to save to to save the resized image.

Conclusion

To resize an image using PIL and maintain its aspect ratio with Python, we can open the image with Image.open.

Then we calculate the new width and height to scale the image to according to the new width.

And then we resize the image with the resize method and save the new image with the save method.