Repository navigation
Expand file tree
/
Copy pathsimple.py
More file actions
48 lines (41 loc) · 1.35 KB
/
Copy pathsimple.py
File metadata and controls
48 lines (41 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
'''making good use of subprocess module to run commands and return the output'''
import subprocess
import shlex
import json
# create a function that runs suprocess and returns the output
def run_command(command):
'''this is the function that runs the command and returns the output'''
cmd = shlex.split(command)
output = subprocess.check_output(cmd)
return output
def run_lsblk(device):
"""
Runs lsblk command and produces JSON output:
lsblk -J -o NAME,SIZE,TYPE,MOUNTPOINT
{
"blockdevices": [
{"name": "vda", "size": "59.6G", "type": "disk", "mountpoint": null,
"children": [
{"name": "vda1", "size": "59.6G", "type": "part", "mountpoint": "/etc/hosts"}
]
}
]
}
"""
command = 'lsblk -J -o NAME,SIZE,TYPE,MOUNTPOINT'
output = run_command(command)
devices = json.loads(output)['blockdevices']
for parent in devices:
if parent['name'] == device:
return parent
for child in parent.get('children', []):
if child['name'] == device:
return child
return None
def main(device):
'''this is the main function that runs the command and prints the output'''
print(f" '{run_lsblk(device)}'")
print("-------------------------")
if __name__ == '__main__':
import sys
main(sys.argv[-1])