common_utils.py 2.03 KB
Newer Older
liuzhe-lz's avatar
liuzhe-lz committed
1
2
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
Deshui Yu's avatar
Deshui Yu committed
3

4
5
import os
import sys
Deshui Yu's avatar
Deshui Yu committed
6
import json
7
import socket
8
from pathlib import Path
chicm-ms's avatar
chicm-ms committed
9
10
import ruamel.yaml as yaml
import psutil
11
from .constants import ERROR_INFO, NORMAL_INFO, WARNING_INFO, COLOR_RED_FORMAT, COLOR_YELLOW_FORMAT
Deshui Yu's avatar
Deshui Yu committed
12
13
14
15
16

def get_yml_content(file_path):
    '''Load yaml file content'''
    try:
        with open(file_path, 'r') as file:
17
            return yaml.load(file, Loader=yaml.Loader)
18
19
    except yaml.scanner.ScannerError as err:
        print_error('yaml file format error!')
chicm-ms's avatar
chicm-ms committed
20
        print_error(err)
21
22
23
24
        exit(1)
    except Exception as exception:
        print_error(exception)
        exit(1)
Deshui Yu's avatar
Deshui Yu committed
25
26
27
28
29
30
31

def get_json_content(file_path):
    '''Load json file content'''
    try:
        with open(file_path, 'r') as file:
            return json.load(file)
    except TypeError as err:
32
        print_error('json file format error!')
chicm-ms's avatar
chicm-ms committed
33
        print_error(err)
Deshui Yu's avatar
Deshui Yu committed
34
35
36
37
        return None

def print_error(content):
    '''Print error information to screen'''
38
    print(COLOR_RED_FORMAT % (ERROR_INFO % content))
Deshui Yu's avatar
Deshui Yu committed
39
40
41
42
43

def print_normal(content):
    '''Print error information to screen'''
    print(NORMAL_INFO % content)

44
45
46
47
def print_warning(content):
    '''Print warning information to screen'''
    print(COLOR_YELLOW_FORMAT % (WARNING_INFO % content))

Deshui Yu's avatar
Deshui Yu committed
48
49
50
51
52
53
54
def detect_process(pid):
    '''Detect if a process is alive'''
    try:
        process = psutil.Process(pid)
        return process.is_running()
    except:
        return False
55
56
57

def detect_port(port):
    '''Detect if the port is used'''
chicm-ms's avatar
chicm-ms committed
58
    socket_test = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
59
60
    try:
        socket_test.connect(('127.0.0.1', int(port)))
SparkSnail's avatar
SparkSnail committed
61
        socket_test.close()
62
63
64
        return True
    except:
        return False
65
66

def get_user():
chicm-ms's avatar
chicm-ms committed
67
    if sys.platform == 'win32':
68
69
70
71
72
73
74
75
        return os.environ['USERNAME']
    else:
        return os.environ['USER']

def get_python_dir(sitepackages_path):
    if sys.platform == "win32":
        return str(Path(sitepackages_path))
    else:
liuzhe-lz's avatar
liuzhe-lz committed
76
        return str(Path(sitepackages_path).parents[2])