Welcome, guest | Sign In | My Account | Store | Cart

This recipe shows how to take a Python function and wrap it with both a web and a command-line interface, somewhat easily, using the hug Python library. The example used shows how to wrap a function that uses the psutil library to get information on disk partitions. So you can see the disk partition info either via the web browser or the command line. The code for the recipe is shown below. It is also possible to wrap multiple functions in the same Python file, and expose all of them via both the web and the command-line.

More information and multiple sample outputs are available here:

https://jugad2.blogspot.in/2017/01/give-your-python-function-webcli-hug.html

Python, 44 lines
 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
"""
hug_pdp.py
Use hug with psutil to show disk partition info 
via Python, CLI or Web interfaces.
Copyright 2017 Vasudev Ram
Web site: https://vasudevram.github.io
Blog: http://jugad2.blogspot.com
Product store: https://gumroad.com/vasudevram
"""

import sys
import psutil
import hug

def get_disk_partition_data():
    dps = psutil.disk_partitions()
    fmt_str = "{:<8} {:<7} {:<7}"

    result = {}
    result['header'] = fmt_str.format("Drive", "Type", "Opts")
    result['detail'] = {}
    for i in (0, 2):
        dp = dps[i]
        result['detail'][str(i)] = fmt_str.format(dp.device, dp.fstype, dp.opts)
    return result

@hug.cli()
@hug.get(examples='drives=0,1')
@hug.local()
def pdp():
    """Get disk partition data"""
    result = get_disk_partition_data()
    return result

@hug.cli()
@hug.get(examples='')
@hug.local()
def pyver():
    """Get Python version"""
    pyver = sys.version[:6]
    return pyver

if __name__ == '__main__':
    pdp.interface.cli()

More information, some discussion, and multiple sample outputs are available here:

https://jugad2.blogspot.in/2017/01/give-your-python-function-webcli-hug.html