Categories
Python Answers

How to use async and await with Python?

Sometimes, we want to use async and await with Python to run async tasks.

In this article, we’ll look at how to use async and await with Python.

How to use async and await with Python?

To use async and await with Python, we can use the asyncio module and the async and await keywords.

For instance, we write:

import asyncio


async def async_foo():
    print("async_foo started")
    await asyncio.sleep(1)
    print("async_foo done")


async def main():
    asyncio.ensure_future(async_foo())
    print('Do some actions 1')
    await asyncio.sleep(1)
    print('Do some actions 2')
    await asyncio.sleep(1)
    print('Do some actions 3')


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

We define the async async_foo function which prints some text and calls asyncio.sleep to pause the function for 1 second.

Then we have the async main function that asyncio.ensure_future method to create a task from the async_foo function and run it.

And then we call asyncio.sleep again with await to pause the function.

Next, we call asyncio.get_event_loop to return the event loop object.

And then we call loop.run_until_complete with main() to run main.

Therefore, we see:

Do some actions 1
async_foo started
Do some actions 2
async_foo done
Do some actions 3

printed with some pauses in between printing each line.

Conclusion

To use async and await with Python, we can use the asyncio module and the async and await keywords.

Categories
Python Answers

How to save a Numpy array as an image with Python?

Sometimes, we want to save a Numpy array as an image with Python.

In this article, we’ll look at how to save a Numpy array as an image with Python.

How to save a Numpy array as an image with Python?

To save a Numpy array as an image with Python, we can use the Image.fromarray method.

For instance, we write:

from PIL import Image
import numpy

w, h = 200, 100
img = numpy.zeros((h, w, 3), dtype=numpy.uint8)

img[:] = (0, 0, 255)

x, y = 40, 20
img[y:y + 30, x:x + 50] = (255, 0, 0)

Image.fromarray(img).convert("RGB").save("art.png")

We call numpy.zeroes to generate an array and assign that to img.

Then we set the entries in img to the (0, 0, 255) tuple.

We then change the colors of some of the entries in the img to (255, 0, 0) with:

x, y = 40, 20
img[y:y + 30, x:x + 50] = (255, 0, 0)

Finally, we call Image.fromarray with the img array to create an image from img.

Then we call convert with 'RGB' and save to convert the image to RGB color and save it to the given path.

Now we should see an art.png image file with a blue background and a red rectangle inside.

Conclusion

To save a Numpy array as an image with Python, we can use the Image.fromarray method.

Categories
Python Answers

How to encrypt and decrypt using PyCrypto AES-256?

Sometimes, we want to encrypt and decrypt using PyCrypto AES-256.

In this article, we’ll look at how to encrypt and decrypt using PyCrypto AES-256.

How to encrypt and decrypt using PyCrypto AES-256?

To encrypt and decrypt using PyCrypto AES-256, we can use the PyCryptodome package.

To install it, we run:

pip install pycryptodome

Then we can use it by writing:

import base64
import hashlib
from Cryptodome.Cipher import AES
from Cryptodome.Random import get_random_bytes

__key__ = hashlib.sha256(b'16-character key').digest()


def encrypt(raw):
    BS = AES.block_size
    pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)

    raw = base64.b64encode(pad(raw).encode('utf8'))
    iv = get_random_bytes(AES.block_size)
    cipher = AES.new(key=__key__, mode=AES.MODE_CFB, iv=iv)
    return base64.b64encode(iv + cipher.encrypt(raw))


def decrypt(enc):
    unpad = lambda s: s[:-ord(s[-1:])]

    enc = base64.b64decode(enc)
    iv = enc[:AES.block_size]
    cipher = AES.new(__key__, AES.MODE_CFB, iv)
    return unpad(
        base64.b64decode(cipher.decrypt(enc[AES.block_size:])).decode('utf8'))


encrypted = encrypt('foo')
decrypted = decrypt(encrypted)
print(encrypted)
print(decrypted)

We create a key with the haslib.sha256 method with a binary string.

We call digest to return a hash of the key.

Then we call encrypt with the raw string to encrypt.

We encrypt by padding the string with the pad function.

Then we encode the string to base64 woth b64encode and encode.

Next, we call get_random_bytes to get some random bytes that we use to create the cipher.

Finally, we return the encrypted string which we generate with b64encode, iv and cipher.encrypt.

Then we define the decrypt function that has the unpad function to unpad the enc encrypted string.

Next, we call b64decode with enc to decode the encrypted string.

Then we get iv from the enc string by slicing it from index 0 to AES.block_size exclusively.

Then we call AES.new with the secret __key__, AES.MODE_CFB, and iv to get the cipher.

And we call unpad with the decoded cipher base64 cipher string to decrypt the string.

A regular string is returned since we called decode on the decrypted string.

Therefore, encrypted is b'zEMqurGW5NgwRwSAJ0lyejwF3Md02LtlC7oxP/SVJJVI/VLwQqpvvw=='

And decrypted is 'foo'.

Conclusion

To encrypt and decrypt using PyCrypto AES-256, we can use the PyCryptodome package.

Categories
Python Answers

How to add an extra column to a NumPy array with Python?

Sometimes, we want to add an extra column to a NumPy array with Python.

In this article, we’ll look at how to add an extra column to a NumPy array with Python.

How to add an extra column to a NumPy array with Python?

To add an extra column to a NumPy array with Python, we can use the append method.

For instance, we write:

import numpy as np
a = np.array([[1,2,3],[2,3,4]])
z = np.zeros((2,1), dtype=np.int64)
b = np.append(a, z, axis=1)
print(b)

We create the array a with np.array.

Then we call np.zeroes with the dimensions of the array passed in as a tuple and the data type set as the value of dtype.

Then we call append with a and z to append z to a.

It returns a new array and we assign that to b.

Therefore, b is:

[[1 2 3 0]
 [2 3 4 0]]

Conclusion

To add an extra column to a NumPy array with Python, we can use the append method.

Categories
Python Answers

How to remove the ANSI escape sequences from a string in Python?

Sometimes, we want to remove the ANSI escape sequences from a string in Python.

In this article, we’ll look at how to remove the ANSI escape sequences from a string in Python.

How to remove the ANSI escape sequences from a string in Python?

To remove the ANSI escape sequences from a string in Python, we can use the regex’s sub method.

For instance, we write:

import re

ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
sometext = 'ls\r\n\x1b[00m\x1b[01;31mexamplefile.zip\x1b[00m\r\n\x1b[01;31m'
s = ansi_escape.sub('', sometext)
print(s)

We call re.compile with a regex string that has the ANSI escape characters.

Then we have the sometext string that has some ANSI escape characters we want to remove.

To do that, we call ansi_escape.sub with an empty string and sometext to return a new string without the escape characters.

Therefore, s is:

ls
examplefile.zip

Conclusion

To remove the ANSI escape sequences from a string in Python, we can use the regex’s sub method.