Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import re
- import subprocess
- import sys
- __author__ = 'baryshev'
- class LogColors:
- def __init__(self):
- """
- """
- pass
- BLACK = '\033[30m'
- GREEN = '\033[92m'
- YELLOW = '\033[93m'
- RED = '\033[91m'
- ON_RED = '\033[41m'
- ON_GREEN = '\033[42m'
- ON_YELLOW = '\033[43m'
- ENDC = '\033[0m'
- class Constants:
- def __init__(self):
- """
- """
- pass
- NO_COLORS = False
- ABORT_ON_FAIL = True
- def process_argv(argv):
- """
- :param argv: list of str
- :return: dict
- """
- args = {}
- for arg in argv[1:]:
- arg = arg.split('=')
- if len(arg) == 2 and len(arg[1]) > 0:
- args[arg[0]] = arg[1]
- else:
- args[arg[0]] = None
- return args
- def get_real_path(path):
- """
- :param path: str
- :return: str
- """
- try:
- return get_cmd_response(cmd='readlink|-f|{}'.format(path))
- except:
- return path
- def get_run_from(current_file):
- """
- :param current_file: str
- :return: str
- """
- if current_file is None:
- current_file = __file__
- return os.path.dirname(os.path.abspath(current_file))
- def run_cmd(cmd):
- """
- :param cmd: str
- """
- log_warning('Running command: {}'.format(cmd.split('|').__str__()))
- process = subprocess.Popen(cmd.split('|'))
- process.communicate()
- code = process.returncode
- if code != 0:
- log_error(message='failed to execute command [{}]'.format(' '.join(cmd.split('|'))))
- log_error(message='exiting with status {}'.format(code))
- if Constants.ABORT_ON_FAIL:
- sys.exit(code)
- def run_cmd_in_background(cmd, stdout_to_pipe=True, stderr_to_pipe=True):
- """
- :param stderr_to_pipe: boolean
- :param cmd: str
- """
- log_warning('Running command: {}'.format(cmd.split('|').__str__()))
- stderr = None
- stdout = None
- if stderr_to_pipe:
- stderr = subprocess.PIPE
- if stdout_to_pipe:
- stdout = subprocess.PIPE
- process = subprocess.Popen(cmd.split('|'), stdout=stdout, stderr=stderr)
- return process
- def get_cmd_response(cmd):
- """
- :param cmd: str
- :return: str
- """
- cmd = cmd.split('|')
- process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
- out, err = process.communicate()
- code = process.returncode
- if code != 0:
- log_error(message='failed to execute command [{}]'.format(' '.join(cmd.split('|'))))
- log_error(message='exiting with status {}'.format(code))
- if Constants.ABORT_ON_FAIL:
- sys.exit(code)
- return out.strip().decode()
- def grep(text, pattern):
- """
- :param text: str
- :param pattern: str
- :return: bool
- """
- reg = re.compile(pattern)
- for line in text.split('\n'):
- if reg.match(line):
- return True
- return False
- def mkdir_p(path_to_dir):
- """
- :param path_to_dir: str
- """
- if not os.path.exists(path_to_dir):
- os.makedirs(path_to_dir)
- def mkdir_for_file(path_to_file):
- """
- :param path_to_file: str
- """
- mkdir_p(path_to_dir=os.path.dirname(path_to_file))
- def read_from_file(filename):
- """
- :param filename: str
- :return: str
- """
- s = open(filename, 'r')
- out = s.read()
- s.close()
- return out.strip()
- def write_to_file(path_to_file, data):
- """
- :param path_to_file: str
- :param data: str
- """
- mkdir_for_file(path_to_file=path_to_file)
- file_to_rewrite = open(path_to_file, 'w')
- file_to_rewrite.write(data)
- file_to_rewrite.close()
- def append_file(path_to_file, data):
- """
- :param path_to_file: str
- :param data: str
- """
- mkdir_for_file(path_to_file=path_to_file)
- file_to_rewrite = open(path_to_file, 'a')
- file_to_rewrite.write(data)
- file_to_rewrite.close()
- def touch_file(path_to_file):
- """
- :param path_to_file: str
- """
- open(path_to_file, 'w').close()
- def copy_file_save_path(path_to_file, new_parent_dir):
- if os.path.exists(path_to_file):
- write_to_file(path_to_file='{}/{}'.format(new_parent_dir, path_to_file), data=read_from_file(path_to_file))
- def write_configfile(path_to_file, section, data=None):
- """
- :param path_to_file: str
- :param section: str
- :param data: list
- """
- if not data:
- data = []
- dirname = os.path.dirname(path_to_file)
- if not os.path.exists(dirname):
- os.makedirs(dirname)
- import configparser
- config = configparser.ConfigParser()
- config.read(path_to_file)
- if section not in config.sections():
- config.add_section(section)
- for key, value in data:
- config.set(section, key, value)
- configfile = open(path_to_file, 'w')
- config.write(configfile)
- configfile.close()
- def log_info(message):
- """
- :param message: str
- """
- if not Constants.NO_COLORS:
- for text in message.split('\n'):
- if len(text) > 0:
- print(LogColors.ON_GREEN + LogColors.BLACK + text + LogColors.ENDC)
- else:
- print('')
- else:
- print(message)
- def log_error(message):
- """
- :param message: str
- """
- if not Constants.NO_COLORS:
- for text in message.split('\n'):
- if len(text) > 0:
- print(LogColors.ON_RED + text + LogColors.ENDC)
- else:
- print('')
- else:
- print(message)
- def log_warning(message):
- """
- :param message: str
- """
- if not Constants.NO_COLORS:
- for text in message.split('\n'):
- if len(text) > 0:
- print(LogColors.ON_YELLOW + LogColors.BLACK + text + LogColors.ENDC)
- else:
- print('')
- else:
- print(message)
- def relaunch_as_root(current_file=None):
- """
- :param current_file: str
- """
- run_from = get_run_from(current_file=current_file)
- os.chdir(run_from)
- if os.geteuid() != 0:
- log_warning(message='script runs under non-privileged user (id:{})\nnow we will try to relaunch as root...'.format(os.geteuid()))
- os.execvp('sudo', ['sudo', 'python'] + sys.argv)
- log_info(message='launch success\n')
Add Comment
Please, Sign In to add comment