Sunday, September 29, 2024

[Python] Tips and trick

-

1. List và dictionary.

Data gốc khi dùng lệnh virsh domiflist <vm_name> trong ảo hóa KVM. Hãy phân tích các giá trị Interface, Type, Source, Model, MAC và đưa chúng vào dictionary nằm trong 1 list. Ví dụ dưới chúng ta lấy thông tin về network của máy ảo tên test-network.

 $ virsh domiflist test-network
 Interface   Type     Source            Model    MAC
--------------------------------------------------------------------
 vnet8       bridge   bridged-network   virtio   52:54:00:75:af:dd
 vnet10      bridge   bridged-network   virtio   52:54:00:bd:bd:29

Bạn có thể sử dụng đoạn code sau để lấy các thành phần đó vào list:

#!/usr/bin/env python3
import subprocess

data = subprocess.check_output('virsh domiflist test-network', shell=True).decode("utf-8").strip('\n')

lines = data.split('\n')[2:]
interfaces = []
for line in lines:
    elements = line.split()
    interface = {'interface': elements[0], 'type': elements[1], 'source': elements[2], 'model': elements[3], 'mac': elements[4]}
    interfaces.append(interface)

Kết quả trả về sẽ là một list các dictionary, mỗi dictionary chứa thông tin của một interface.

[{'interface': 'vnet8', 'type': 'bridge', 'source': 'bridged-network', 'model': 'virtio', 'mac': '52:54:00:75:af:dd'}, {'interface': 'vnet10', 'type': 'bridge', 'source': 'bridged-network', 'model': 'virtio', 'mac': '52:54:00:bd:bd:29'}]

Kết quả khi sử dụng hàm for i in interfaces.

{'interface': 'vnet8', 'type': 'bridge', 'source': 'bridged-network', 'model': 'virtio', 'mac': '52:54:00:75:af:dd'}
{'interface': 'vnet10', 'type': 'bridge', 'source': 'bridged-network', 'model': 'virtio', 'mac': '52:54:00:bd:bd:29'}

2. Chuyển đổi từ hàng dọc thành hàng ngang và chèn thêm ký tự ở giữa.

string = """ha
dang
hoang"""
separator = "-"
result = separator.join(string.splitlines())
print(result)

-> Output: ha-dang-hoang

LEAVE A REPLY

Please enter your comment!
Please enter your name here

4,956FansLike
256FollowersFollow
223SubscribersSubscribe
spot_img

Related Stories