Ejemplo n.º 1
0
def config_file_read(config_file, alias, db):
    """
    read config file
    """

    if alias is None:
        alias = config_file

    if myos.iswin() or myos.islinux():
        config = configparser.ConfigParser()
        config.read(config_file)
        with open(config_file) as f:
            name = f.name

        desc = 'Nothing'
        if (const.CONFIG_DEFAULT in config
                and const.CONFIG_DESC in config[const.CONFIG_DEFAULT]):
            desc = config[const.CONFIG_DEFAULT][const.CONFIG_DESC]

        config[const.CONFIG_DEFAULT] = {
            const.CONFIG_PATH: name,
            const.CONFIG_ALIAS: alias,
            const.CONFIG_DESC: desc
        }

    db[alias] = config

    return ''
Ejemplo n.º 2
0
def path_to(from_path: str, to_path: str):
    """
    Warning: this function is OS dependent

    >>> path_to('/home/john/coding', '/home/alice/Download')
    '../../alice/Download'
    >>> path_to('/home/john/coding', '/home/john/coding/tmp')
    './tmp'
    >>> try:
    ...     path_to('d:\\abc', 'c:\\abc\\def')
    ... except ValueError as ex:
    ...     print(ex)
    Paths don't have the same drive
    """
    from_path = os.path.abspath(from_path)
    to_path = os.path.abspath(to_path)

    if iswin() and os.path.splitdrive(from_path) != os.path.splitdrive(to_path):
        return to_path
    else:
        common_path = os.path.commonpath([from_path, to_path])

    from_extra_path = from_path.split(common_path)[1]
    to_extra_path = to_path.split(common_path)[1]

    parpath = os.path.sep.join([os.pardir] * path_level(from_extra_path))

    if parpath:
        target_path = parpath + to_extra_path
    else:
        target_path = os.curdir + to_extra_path

    return target_path
Ejemplo n.º 3
0
def __clojure_find():
    """
    Dynamic find the matched clojure.jar
    """
    spc=''
    if myos.iswin():
        spc=';'
    elif myos.islinux():
        spc=':'

    p=''
    if 'classpath' in os.environ:
        p=os.environ['classpath'].split(spc)
    elif 'CLASSPATH' in os.environ:
        p=os.environ['CLASSPATH'].split(spc)

    p=seh.parseStr(p)
    file=[]
    for path in p:
        result=search.file_search(dirname=path,
                                    inner=True,
                                    pattern=const.CLOJURE_JAR)[0]         
        if  result!=[]:
             [file.append(item) for item in result]

                
    return file
Ejemplo n.º 4
0
def config_file_read(config_file,alias,db):
    """
    read config file
    """
        
    if alias==None:
        alias=config_file
        
    if myos.iswin() or myos.islinux():
        config=configparser.ConfigParser()
        config.read(config_file)
        with open(config_file) as f:
            name=f.name

        desc='Nothing'
        if (const.CONFIG_DEFAULT in config and
            const.CONFIG_DESC in config[const.CONFIG_DEFAULT]):
            
            desc=config[const.CONFIG_DEFAULT][const.CONFIG_DESC]
        
        config[const.CONFIG_DEFAULT]={const.CONFIG_PATH:name,
                                      const.CONFIG_ALIAS:alias,
                                      const.CONFIG_DESC:desc}

        
    db[alias]=config


    return ''
Ejemplo n.º 5
0
 def run(self, cmdline, **kwargs):
     if ver.islinux():
         # os.spawnv(os.P_DETACH,pyfile,(pyfile,cmdline))
         self.popen = subprocess.Popen('%s %s' % (pyfile, cmdline), **kwargs)
     elif ver.iswin():
         # os.spawnv(os.P_NOWAIT,pyfile,(pyfile,cmdline))
         self.popen = subprocess.Popen('%s %s' % (pyfile, cmdline), **kwargs)
Ejemplo n.º 6
0
def path_to(from_path: str, to_path: str):
    """
    Warning: this function is OS dependent

    >>> path_to('/home/john/coding', '/home/alice/Download')
    '../../alice/Download'
    >>> path_to('/home/john/coding', '/home/john/coding/tmp')
    './tmp'
    >>> try:
    ...     path_to('d:\\abc', 'c:\\abc\\def')
    ... except ValueError as ex:
    ...     print(ex)
    Paths don't have the same drive
    """
    from_path = os.path.abspath(from_path)
    to_path = os.path.abspath(to_path)

    if iswin(
    ) and os.path.splitdrive(from_path) != os.path.splitdrive(to_path):
        return to_path
    else:
        common_path = os.path.commonpath([from_path, to_path])

    from_extra_path = from_path.split(common_path)[1]
    to_extra_path = to_path.split(common_path)[1]

    parpath = os.path.sep.join([os.pardir] * path_level(from_extra_path))

    if parpath:
        target_path = parpath + to_extra_path
    else:
        target_path = os.curdir + to_extra_path

    return target_path
Ejemplo n.º 7
0
def __clojure_find():
    """
    Dynamic find the matched clojure.jar
    """
    spc = ''
    if myos.iswin():
        spc = ';'
    elif myos.islinux():
        spc = ':'

    p = ''
    if 'classpath' in os.environ:
        p = os.environ['classpath'].split(spc)
    elif 'CLASSPATH' in os.environ:
        p = os.environ['CLASSPATH'].split(spc)

    p = seh.parseStr(p)
    file = []
    for path in p:
        result = search.file_search(dirname=path,
                                    inner=True,
                                    pattern=const.CLOJURE_JAR)[0]
        if result != []:
            [file.append(item) for item in result]

    return file
Ejemplo n.º 8
0
    def run(self, cmdline, **kwargs):
        assert ver.iswin()
        # os.system('  '.join(['start',cmdline])) #maybe create new window
        shell = kwargs.get('shell', True)
        from minghu6.algs.userdict import remove_key
        kwargs = remove_key(kwargs, 'shell')

        subprocess.call('  '.join(['start', cmdline]), shell=shell, **kwargs)
Ejemplo n.º 9
0
    def run(self, cmdline, **kwargs):
        assert ver.iswin()
        # os.system('  '.join(['start',cmdline])) #maybe create new window
        shell = kwargs.get('shell', True)
        from minghu6.algs.userdict import remove_key
        kwargs = remove_key(kwargs, 'shell')

        subprocess.call('  '.join(['start', cmdline]), shell=shell, **kwargs)
Ejemplo n.º 10
0
def get_drivers():
    if not iswin():
        raise OSError('only support in Windows')
        
    lp_buffer = ctypes.create_string_buffer(78)
    ctypes.windll.kernel32.GetLogicalDriveStringsA(ctypes.sizeof(lp_buffer), lp_buffer)
    drivers = lp_buffer.raw.split(b'\x00')
    
    return [each_driver.decode()[:2] for each_driver in drivers if each_driver and os.path.isdir(each_driver)]
Ejemplo n.º 11
0
 def run(self, cmdline, **kwargs):
     if ver.islinux():
         # os.spawnv(os.P_DETACH,pyfile,(pyfile,cmdline))
         self.popen = subprocess.Popen('%s %s' % (pyfile, cmdline),
                                       **kwargs)
     elif ver.iswin():
         # os.spawnv(os.P_NOWAIT,pyfile,(pyfile,cmdline))
         self.popen = subprocess.Popen('%s %s' % (pyfile, cmdline),
                                       **kwargs)
Ejemplo n.º 12
0
def find_exec_file(path):
    exec_file_list = []
    for file in os.listdir(path):
        if iswin():
            if os.path.splitext(file)[1] == '.exe':
                exec_file_list.append(os.path.splitext(file)[0])
        else:
            if os.access(os.path.join(path, file), os.X_OK):
                exec_file_list.append(os.path.splitext(file)[0])

    return exec_file_list
Ejemplo n.º 13
0
def where_pth():
    if islinux():
        for path in sys.path:
            if os.path.basename(path) == 'dist-packages':
                return path

    elif iswin():
        return os.path.split(sys.executable)[0]

    else:
        raise Exception('Not Implemented!')
Ejemplo n.º 14
0
def find_exec_file(path):
    exec_file_list = []
    for file in os.listdir(path):
        if iswin():
            if os.path.splitext(file)[1] == '.exe':
                exec_file_list.append(os.path.splitext(file)[0])
        else:
            if os.access(os.path.join(path, file), os.X_OK):
                exec_file_list.append(os.path.splitext(file)[0])

    return exec_file_list
Ejemplo n.º 15
0
def where_pth():
    if islinux():
        for path in sys.path:
            if os.path.basename(path)=='dist-packages':
                return path

    elif iswin():
        return os.path.split(sys.executable)[0]

    else:
        raise Exception('Not Implemented!')
Ejemplo n.º 16
0
def is_relative_path(path):
    """don't care about if the path exists"""
    if iswin():
        if not os.path.splitdrive(path)[0]:
            return False
        else:
            return True
    else:
        if path.startswith('/'):
            return False
        else:
            return True
Ejemplo n.º 17
0
def get_drivers():
    if not iswin():
        raise OSError('only support in Windows')

    lp_buffer = ctypes.create_string_buffer(78)
    ctypes.windll.kernel32.GetLogicalDriveStringsA(ctypes.sizeof(lp_buffer),
                                                   lp_buffer)
    drivers = lp_buffer.raw.split(b'\x00')

    return [
        each_driver.decode()[:2] for each_driver in drivers
        if each_driver and os.path.isdir(each_driver)
    ]
Ejemplo n.º 18
0
def selftest():
    '''
    only for test...
    '''
    file = 'echo.py'
    os.system('echo print(\'hi\') > %s' % file)
    input('default mode ...')
    PortableLauncher(file, file)()

    input('system mode ...')
    System(file, file)()

    if ver.iswin():
        input('DOS start mode...')
        StartArgs(file, file, shell=True)()
Ejemplo n.º 19
0
def selftest():
    '''
    only for test...
    '''
    file = 'echo.py'
    os.system('echo print(\'hi\') > %s' % file)
    input('default mode ...')
    PortableLauncher(file, file)()

    input('system mode ...')
    System(file, file)()

    if ver.iswin():
        input('DOS start mode...')
        StartArgs(file, file, shell=True)()
Ejemplo n.º 20
0
def monitor_loop(dirs_to_monitor=dirs_to_monitor, no_dump=False):
    if iswin():
        start_monitor = start_monitor_win
    else:
        raise NotImplementedError

    for path in dirs_to_monitor:
        monitor_thread = threading.Thread(target=start_monitor, args=(path, no_dump), daemon=True)
        print("Spawning monitoring thread for path: %s" % os.path.abspath(path))
        monitor_thread.start()

    def handler_kill(signum, frame):
        raise SystemExit

    signal.signal(signal.SIGINT, handler_kill)
    while True:  # for main thread can catch signal
        pass
Ejemplo n.º 21
0
def find_wrapper(start_dir, pattern):
        
    if not isiterable(pattern):
        pattern = [pattern]
        
    command_runner = CommandRunner()
    if iswin():
        cmd = 'where /R "{start_dir}" {pattern}'.format(start_dir=start_dir, pattern=' '.join(pattern))
    else:
        cmd = 'find {start_dir} {pattern}'.format(
            start_dir=start_dir,
            pattern=' '.join(['-name "%s"' % each_pattern for each_pattern in pattern])
        )
    
    for line in command_runner.run(cmd):
        if os.path.exists(line):
            yield line
Ejemplo n.º 22
0
def find_wrapper(start_dir, pattern):

    if not isiterable(pattern):
        pattern = [pattern]

    command_runner = CommandRunner()
    if iswin():
        cmd = 'where /R "{start_dir}" {pattern}'.format(
            start_dir=start_dir, pattern=' '.join(pattern))
    else:
        cmd = 'find {start_dir} {pattern}'.format(
            start_dir=start_dir,
            pattern=' '.join(
                ['-name "%s"' % each_pattern for each_pattern in pattern]))

    for line in command_runner.run(cmd):
        if os.path.exists(line):
            yield line
Ejemplo n.º 23
0
def monitor_loop(dirs_to_monitor=dirs_to_monitor, no_dump=False):
    if iswin():
        start_monitor = start_monitor_win
    else:
        raise NotImplementedError

    for path in dirs_to_monitor:
        monitor_thread = threading.Thread(target=start_monitor,
                                          args=(path, no_dump),
                                          daemon=True)
        print("Spawning monitoring thread for path: %s" %
              os.path.abspath(path))
        monitor_thread.start()

    def handler_kill(signum, frame):
        raise SystemExit

    signal.signal(signal.SIGINT, handler_kill)
    while True:  # for main thread can catch signal
        pass
Ejemplo n.º 24
0
def alarm(timeout):
    if iswin():

        def exit_handle(signal, frame):
            raise TimeoutError

        signal.signal(signal.SIGINT, exit_handle)

        alarm = _Alarm(timeout)
        alarm.start()
        del alarm

    else:
        from signal import alarm

        def timeout_handle(signal, frame):
            raise TimeoutError

        signal.signal(signal.SIGINT, timeout_handle)

        alarm(timeout)
Ejemplo n.º 25
0
def clojure_find(db):
    """
    Lazy  find using __clojure_find and shelve
    """
    str_clojure = ''
    if myos.iswin() or myos.islinux():

        file = []
        valid_file = []
        if const.CLOJURE in db:
            file = db[const.CLOJURE]
            for item in file:
                if os.path.exists(item):
                    valid_file.append(item)

        if len(valid_file) == 0:
            valid_file = __clojure_find()
            db[const.CLOJURE] = valid_file

        str_clojure = valid_file[0]
        db.close()
    return str_clojure
Ejemplo n.º 26
0
def clojure_find(db):
    """
    Lazy  find using __clojure_find and shelve
    """
    str_clojure = ''
    if myos.iswin() or myos.islinux():

        file = []
        valid_file = []
        if const.CLOJURE in db:
            file = db[const.CLOJURE]
            for item in file:
                if os.path.exists(item):
                    valid_file.append(item)

        if len(valid_file) == 0:
            valid_file = __clojure_find()
            db[const.CLOJURE] = valid_file

        str_clojure = valid_file[0]
        db.close()
    return str_clojure
Ejemplo n.º 27
0
    def run(self, cmdline, **kwargs):
        assert ver.iswin()

        os.startfile(cmdline, **kwargs)
Ejemplo n.º 28
0

class Top_Level(LaunchMode):
    '''
    run in a new window ,same process;...need GUI Info
    '''
    def run(self, cmdline, **kwargs):
        assert False, 'Sorry - mode not yet implemented'


#
# choose a portable launcher for self platform
# maybe need refinnement later
#

if ver.iswin():
    # PortableLauncher=Spawn
    PortableLauncher = Popen
else:
    PortableLauncher = Fork


class QuietPortableLauncher(PortableLauncher):
    '''
    do nothing excpt redefine the announce doing nothing
    '''
    def announce(self, text):
        pass


def selftest():
Ejemplo n.º 29
0
def ignore_signals():
    if not iswin():
        signal.signal(signal.SIGTSTP, signal.SIG_IGN)

    signal.signal(signal.SIGINT, signal.SIG_IGN)
Ejemplo n.º 30
0
    def run(self, cmdline, **kwargs):
        assert ver.iswin()

        os.startfile(cmdline, **kwargs)
Ejemplo n.º 31
0
def java_mode(alias, iteral, __compile, main, db):
    """
    reference const defination
    """
    dic = db[alias]

    config_dic = {}

    java_str = ''
    cp_str = ''
    d_str = ''

    target_str = ''
    main_str = ''

    spc = ''
    if myos.iswin():
        spc = ';'
    elif myos.islinux():
        spc = ':'

    if myos.iswin():
        if __compile:
            config_dic = dic[const.COMPILE]
            if const.JAVA_D in config_dic:
                d_str = config_dic[const.JAVA_D]
                java_str = ' '.join(['javac', '-d ' + d_str])

            if const.JAVA_CP in config_dic:
                cp_str = config_dic[const.JAVA_CP]
                java_str = ' '.join([java_str, '-cp ' + cp_str])

            if const.JAVA_TARGET in config_dic:
                """"
                consider of more than one target
                """
                target_str = config_dic[const.JAVA_TARGET]
                targets = seh.parseStr(target_str.split(spc))

                assert (len(targets) != 0)

                tmp_str = ''
                link = '&&'
                for target in targets:
                    tmp_str += '  '.join([java_str, target])
                    tmp_str += link
                    # print('??????')

                java_str = tmp_str[:-len(link)]

        else:  # run
            config_dic = dic[const.RUN]

            if const.JAVA_CP in config_dic:
                cp_str = config_dic[const.JAVA_CP]
                java_str = ' '.join(['java', '-cp ' + cp_str])

            if const.JAVA_MAIN in config_dic:
                if main == list():
                    main_str = config_dic[const.JAVA_MAIN]
                else:
                    main_str = main

                java_str = ' '.join([java_str, main_str])

    elif myos.islinux():
        raise Exception('UnImplemented')

    # print(iteral)
    for item in iteral:
        java_str = ' '.join([java_str, item])

    return java_str
Ejemplo n.º 32
0
Options:
  watch-path  default ["C:\\WINDOWS\\Temp", tempfile.gettempdir()]
  --no-dump   not dump modified file content

"""
__version__ = '1.0'
import os
import signal
import tempfile
import threading

import cchardet as chardet
from docopt import docopt
from minghu6.etc.version import iswin

if iswin():
    dirs_to_monitor = ["C:\\WINDOWS\\Temp", tempfile.gettempdir()]
else:
    dirs_to_monitor = [tempfile.gettempdir()]

# file modification constants
FILE_CREATED = 1
FILE_DELETED = 2
FILE_MODIFIED = 3
FILE_RENAMED_FROM = 4
FILE_RENAMED_TO = 5


def start_monitor_win(path_to_watch, no_dump=False):
    import win32file
    import win32con
Ejemplo n.º 33
0
def get_env_var_sep():
    if iswin():
        return ';'
    else:
        return ':'  # Linux, Unix, OS X
Ejemplo n.º 34
0
def java_mode(alias,iteral,__compile,main,db):
    """
    reference const defination
    """
    dic=db[alias]
    
    config_dic={}
    
    java_str=''
    cp_str=''
    d_str=''
    
    target_str=''
    main_str=''
    
    spc=''
    if myos.iswin():
        spc=';'
    elif myos.islinux():
        spc=':'

        
    if myos.iswin():
        if __compile:
            config_dic=dic[const.COMPILE]
            if const.JAVA_D in config_dic:
                d_str=config_dic[const.JAVA_D]
                java_str=' '.join(['javac','-d '+d_str])
                
            if const.JAVA_CP in config_dic:
                cp_str=config_dic[const.JAVA_CP]
                java_str=' '.join([java_str,'-cp '+cp_str])
                
            if const.JAVA_TARGET in config_dic:
                '''
                consider of more than one target
                '''   
                target_str=config_dic[const.JAVA_TARGET]
                targets=seh.parseStr(target_str.split(spc))

                assert (len(targets)!=0)
                
                tmp_str=''
                link='&&'
                for target in targets:
                    tmp_str+='  '.join([java_str,target])
                    tmp_str+=link
                    #print('??????')
                
                java_str=tmp_str[:-len(link)]
                
        else:# run
            config_dic=dic[const.RUN]

            if const.JAVA_CP in config_dic:
                cp_str=config_dic[const.JAVA_CP]
                java_str=' '.join(['java','-cp '+cp_str])
                
            if const.JAVA_MAIN in config_dic:
                if main==list():
                    main_str=config_dic[const.JAVA_MAIN]
                else:
                    main_str=main
                    
                java_str=' '.join([java_str,main_str])
                
    elif myos.islinux():    
        raise Exception('UnImplemented')

    #print(iteral)
    for item in iteral:
        java_str=' '.join([java_str,item])

    return java_str
Ejemplo n.º 35
0
Options:
  watch-path  default ["C:\\WINDOWS\\Temp", tempfile.gettempdir()]
  --no-dump   not dump modified file content

"""
__version__ = '1.0'
import os
import signal
import tempfile
import threading

import cchardet as chardet
from docopt import docopt
from minghu6.etc.version import iswin

if iswin():
    dirs_to_monitor = ["C:\\WINDOWS\\Temp", tempfile.gettempdir()]
else:
    dirs_to_monitor = [tempfile.gettempdir()]

# file modification constants
FILE_CREATED = 1
FILE_DELETED = 2
FILE_MODIFIED = 3
FILE_RENAMED_FROM = 4
FILE_RENAMED_TO = 5


def start_monitor_win(path_to_watch, no_dump=False):
    import win32file
    import win32con
Ejemplo n.º 36
0
def ignore_signals():
    if not iswin():
        signal.signal(signal.SIGTSTP, signal.SIG_IGN)

    signal.signal(signal.SIGINT, signal.SIG_IGN)
Ejemplo n.º 37
0
class Top_Level(LaunchMode):
    '''
    run in a new window ,same process;...need GUI Info
    '''

    def run(self, cmdline, **kwargs):
        assert False, 'Sorry - mode not yet implemented'


#
# choose a portable launcher for self platform
# maybe need refinnement later
#

if ver.iswin():
    # PortableLauncher=Spawn
    PortableLauncher = Popen
else:
    PortableLauncher = Fork


class QuietPortableLauncher(PortableLauncher):
    '''
    do nothing excpt redefine the announce doing nothing
    '''

    def announce(self, text):
        pass