コード例 #1
0
def update_file(filename: str, url: str) -> bool:
    """Check and update file compares with remote_url

    Args:
        filename: str. Local filename, normally it's `__file__`
        url: str or urllib.request.Request object. Remote url of raw file content. Use urllib.request.Request object for headers.
    Returns:
        bool: file updated or not
    """
    def compare(s1, s2):
        return s1 == s2, len(s2) - len(s1)

    if not url or not filename:
        return False
    try:
        raw_codes = read_url(url)
        with open(filename, "rb") as f:
            current_codes = f.read().replace(b"\r", b"")
        is_same, diff = compare(current_codes, raw_codes)
        if is_same:
            cit.info("{} is already up-to-date.".format(filename))
            return False
        else:
            cit.ask("A new version is available. Update? (Diff: {})".format(diff))
            if cit.get_choice(["Yes", "No"]) == "Yes":
                with open(filename, "wb") as f:
                    f.write(raw_codes)
                cit.info("Update Success.")
                return True
            else:
                cit.warn("Update Canceled")
                return False
    except Exception as e:
        cit.err("{f} update failed: {e}".format(f=filename, e=e))
        return False
コード例 #2
0
ファイル: djangoTool.py プロジェクト: kyan001/Duetime
def load_config(config_file):
    config = configparser.ConfigParser()
    config.read(config_file)
    conf = config['DEFAULT']
    conf_dd = config['DATADUMP']
    if conf.get('version') and conf.get('version') not in __version__:
        cit.warn("Different versions detected: {cfile} ({cver}) and djangoTool.py ({pver})".format(cfile=config_file, cver=conf.get('version'), pver=__version__))
    return conf, conf_dd
コード例 #3
0
ファイル: uwsgiTool.py プロジェクト: kyan001/Duetime
def show_running_status(pid_file):
    """check if this uwsgi is already running"""
    if os.path.exists(pid_file):
        cit.warn("uwsgi is running @ " + pid_file)
        return True
    else:
        cit.info("No uwsgi running")
        return False
コード例 #4
0
def generate_filepath(filename):
    home_dir = os.path.expanduser('~')
    cit.info("Home Dir\t: {}".format(home_dir))
    if not os.path.isdir(home_dir):
        cit.warn('Home Dir does not exist, creating it')
        os.makedirs(home_dir)
    new_file = os.path.join(home_dir, filename)
    cit.info("Target File\t: {}".format(new_file))
    return new_file
コード例 #5
0
ファイル: KyanToolKit.py プロジェクト: kyan001/PyKyanToolKit
 def readFile(cls, filepath):
     """Try different encoding to open a file in readonly mode"""
     for mode in ("utf-8", 'gbk', 'cp1252', 'windows-1252', 'latin-1'):
         try:
             with open(filepath, mode='r', encoding=mode) as f:
                 content = f.read()
                 cit.info('以 {} 格式打开文件'.format(mode))
                 return content
         except UnicodeDecodeError:
             cit.warn('打开文件:尝试 {} 格式失败'.format(mode))
     return None
コード例 #6
0
def run_cmd(cmd: str) -> bool:
    """Run command and show if success or failed

    Args:
        cmd: string
    Returns:
        bool: Does this command run successfully
    """
    SUCCESS_CODE = 0
    cit.echo(cmd, "command")
    is_success = (os.system(cmd) == SUCCESS_CODE)
    if not is_success:
        cit.warn("Command Failed")
コード例 #7
0
def read_file(filepath, *args, **kwargs) -> str:
    """Try different encoding to open a file in readonly mode."""
    for mode in ("utf-8", "gbk", "cp1252", "windows-1252", "latin-1", "ascii"):
        try:
            with open(filepath, *args, encoding=mode, **kwargs) as f:
                content = f.read()
                cit.info("File is read in {} mode.".format(mode))
                return content
        except UnicodeDecodeError:
            cit.warn("File cannot be opened in {} mode".format(mode))
    with open(filepath, *args, encoding='ascii', errors='surrogateescape', **kwargs) as f:
        content = f.read()
        cit.info("File is read in ASCII surrogate escape mode.")
        return content
コード例 #8
0
def generate_UDP_file(Phraser: object, output: str, phrases: list):
    if not Phraser:
        raise Exception("Phraser must provided!")
    if not output:
        raise Exception("No output filename provided!")
    phraser = Phraser(phrases)
    filepath = os.path.join(GENERATED_DIR, output)
    if os.path.exists(filepath):
        cit.ask("'{}' is already exists. Overwrite it?".format(filepath))
        if cit.get_choice(['Yes', 'No']) == 'Yes':
            os.remove(filepath)
        else:
            cit.warn("Output is not overwrited. No file generated.")
            return
    phraser.to_file(filepath)
    cit.info("'{o}' is generated, {length} phrases.".format(
        o=output, length=len(phraser.phrases)))
コード例 #9
0
def apply_config(config_name):
    current_dir = os.path.dirname(os.path.realpath(__file__))
    new_conf = os.path.join(current_dir, "config" + config_name)
    target_conf = generate_filepath(config_name)
    if os.path.exists(target_conf):
        cit.warn("Target file is already exist.")
        diffs = diff(target_conf, new_conf)
        if not diffs:
            cit.warn("Files are same, stop configing.")
            return True
        cit.warn("Diffs found:\n" + "".join(diffs))
        backup = '{}.old'.format(target_conf)
        os.rename(target_conf, backup)
        cit.warn("Old config file renamed as {}".format(backup))
    return copy(new_conf, target_conf)
コード例 #10
0
ファイル: KyanToolKit.py プロジェクト: kyan001/PyKyanToolKit
    def updateFile(cls, file_, url):
        """Check and update file compares with remote_url

        Args:
            file_: str. Local filename. Normally it's __file__
            url: str. Remote url of raw file content. Normally it's https://raw.github.com/...
        Returns:
            bool: file updated or not
        """
        def compare(s1, s2):
            return s1 == s2, len(s2) - len(s1)

        if not url or not file_:
            return False
        try:
            req = urllib.request.urlopen(url)
            raw_codes = req.read()
            with open(file_, 'rb') as f:
                current_codes = f.read().replace(b'\r', b'')
            is_same, diff = compare(current_codes, raw_codes)
            if is_same:
                cit.info("{} is already up-to-date.".format(file_))
                return False
            else:
                cit.ask("A new version is available. Update? (Diff: {})".format(diff))
                if cit.get_choice(['Yes', 'No']) == 'Yes':
                    with open(file_, 'wb') as f:
                        f.write(raw_codes)
                    cit.info("Update Success.")
                    return True
                else:
                    cit.warn("Update Canceled")
                    return False
        except Exception as e:
            cit.err("{f} update failed: {e}".format(f=file_, e=e))
            return False
コード例 #11
0
def generate_filepath(filename):
    home_dir = os.path.expanduser('~')
    cit.info("Home Dir\t: {}".format(home_dir))
    if not os.path.isdir(home_dir):
        cit.warn('Home Dir does not exist, creating it', lvl=1)
        os.makedirs(home_dir)
    new_file = os.path.join(home_dir, filename)
    cit.info("Target File\t: {}".format(new_file))
    if os.path.exists(new_file):
        backup = '{}.old'.format(new_file)
        os.rename(new_file, backup)
        cit.warn("Target file is already exist.", lvl=1)
        cit.warn('Old target file renamed as {}'.format(backup), lvl=1)
    return new_file
コード例 #12
0
 def test_warn(self):
     with patch("sys.stdout", new=StringIO()) as fake_out:
         cit.warn("ABC")
         self.assertEqual(fake_out.getvalue(), "| (Warning) ABC\n")
コード例 #13
0
 def test_warn(self):
     cit.warn("ABC")
     self.assertEqual(self.fakeout.readline(ansi=False),
                      "| (Warning) ABC\n")
コード例 #14
0
ファイル: uwsgiTool.py プロジェクト: kyan001/Portal-Django
# -Pre-conditions Check-------------------------------------------
ktk.needPlatform("linux")

# -set params-----------------------------------------------------
# config file
uwsgi_xml = "./uwsgi.xml"
if os.path.isfile(uwsgi_xml):
    cit.info("uwsgi config file: " + uwsgi_xml)
else:
    cit.err("uwsgi config file not found: " + uwsgi_xml)
# pid file
dir_name = os.path.basename(os.path.dirname(os.path.abspath(__file__)))
pid_file = "/var/run/uwsgi_{}.pid".format(dir_name)
if os.path.exists(pid_file):
    cit.warn("uwsgi is running @ " + pid_file)
else:
    cit.info("No uwsgi running")
# choice
operations = ["start", "stop", "reload"]
oprtn = ""
if len(sys.argv) != 2:
    oprtn = cit.get_choice(operations)
elif sys.argv[1] in operations:
    oprtn = sys.argv[1]
else:
    cit.err("Wrong Params: " + sys.argv[1])
    cit.bye()

# -run commands---------------------------------------------------
if "start" == oprtn: