コード例 #1
0
ファイル: MakeApp.py プロジェクト: hewenwork/First
 def make(file_path, file_name=None):
     if file_name is None:
         file_name = os.path.basename(file_path).split(".")[0]
     current_dir = os.path.dirname(__file__)
     temp_dir = os.path.join(current_dir, r"justonemin")
     option = [
         f"--name={file_name}",
         f"--distpath={current_dir}",
         f"--specpath={temp_dir}",
         f"--workpath={temp_dir}",
         "--noconsole",
         "--onefile",
         "--clean",
         "--noconfirm",
         "--log-level=ERROR",
         "--hiddenimport=uvicorn",
         # "--paths=F:\Workspace\First",
         # "--exclude-module pywin32-stypes",
         # f"--additional-hooks-dir f:\\python\\lib\\site-packages",
         # '--add-binary=%s' % os.path.join('resource', 'path', '*.png'),
         # '--add-data=%s' % os.path.join('resource', 'path', '*.txt'),
         file_path
     ]
     ico = r"ico.ico"
     if os.path.exists(ico):
         ico_path = os.path.abspath(r"ico.ico")
         option.insert(0, f"--icon={ico_path}")
     try:
         __main__.run(option)
     except Exception as e:
         messagebox.showwarning(message=e)
         exit()
     else:
         shutil.rmtree(temp_dir)
コード例 #2
0
def test_datas(tmp_path):
    """Test fonts and images."""
    app_name = "userapp"
    workpath = tmp_path / "build"
    distpath = tmp_path / "dist"
    app = tmp_path / (app_name + ".py")
    app.write_text("""
import os
import kivymd
from kivy.core.text import LabelBase

fonts = os.listdir(kivymd.fonts_path)
print(fonts)
assert "Roboto-Regular.ttf" in fonts
assert "materialdesignicons-webfont.ttf" in fonts
print(LabelBase._fonts.keys())
assert "Roboto" in LabelBase._fonts.keys()  # NOQA
assert "Icons" in LabelBase._fonts.keys()  # NOQA

images = os.listdir(kivymd.images_path)
print(images)
assert "folder.png" in images
assert "rec_shadow.atlas" in images
""")
    pyi_main.run([
        "--workpath",
        str(workpath),
        "--distpath",
        str(distpath),
        "--specpath",
        str(tmp_path),
        str(app),
    ])
    subprocess.run([str(distpath / app_name / app_name)], check=True)
コード例 #3
0
def package():
    output = str(ROOT / 'windows')
    shutil.rmtree(output, ignore_errors=True)
    os.makedirs(output, exist_ok=True)
    setup_command()
    pyi.run()
    shutil.rmtree(output, ignore_errors=True)
コード例 #4
0
ファイル: conftest.py プロジェクト: jayfk/pyinstaller
    def _test_building(self, args):
        """
        Run building of test script.

        :param args: additional CLI options for PyInstaller.

        Return True if build succeded False otherwise.
        """
        default_args = ['--debug', '--noupx',
                '--specpath', self._specdir,
                '--distpath', self._distdir,
                '--workpath', self._builddir,
                '--path', _MODULES_DIR]
        default_args.extend(['--debug', '--log-level=DEBUG'])

        # Choose bundle mode.
        if self._mode == 'onedir':
            default_args.append('--onedir')
        elif self._mode == 'onefile':
            default_args.append('--onefile')
        # if self._mode is None then just the spec file was supplied.

        pyi_args = [self.script] + default_args + args
        # TODO fix return code in running PyInstaller programatically
        PYI_CONFIG = configure.get_config(upx_dir=None)
        # Override CACHEDIR for PyInstaller and put it into self.tmpdir
        PYI_CONFIG['cachedir'] = self._tmpdir
        # Speed up tests by reusing copy of basic module graph object.
        PYI_CONFIG['tests_modgraph'] = copy.deepcopy(self._modgraph)

        pyi_main.run(pyi_args, PYI_CONFIG)
        retcode = 0

        return retcode == 0
コード例 #5
0
def package(prefix):
    """基于PyInstaller打包编译为单可执行文件"""
    opts = [
        '{}app.spec'.format(prefix), '--distpath={}dist'.format(prefix),
        '--workpath={}build'.format(prefix)
    ]
    run(opts)
コード例 #6
0
ファイル: to_exe.py プロジェクト: ZhangYupengCHY/recommend
def py2exe_to_only_exe():
    opts = [r'D:\AD-Helper1\ad_helper\recommend\py2_exe\py2exe.py',
            '-F', '-w', r'--distpath=D:\AD-Helper1\ad_helper\recommend\py2_exe\monthly_upload',
            r'--workpath=D:\AD-Helper1\ad_helper\recommend\py2_exe\monthly_upload\history',
            r'--specpath=D:\AD-Helper1\ad_helper\recommend\py2_exe\monthly_upload\build',
            r'-n=Month_Data_Sum_PRO',]
    run(opts)
コード例 #7
0
def test_RecursionError_prints_message(tmpdir, large_import_chain,
                                       monkeypatch):
    """
    modulegraph is recursive and thus triggers RecursionError if
    nesting of imported modules is to deep. Ensure a respective
    informative message is printed if recursion error occurs.
    """
    if is_py37 and is_win:
        pytest.xfail("worker is know to crash for Py 3.7, 3.8 on Windows")
    path, script = large_import_chain

    default_args = [
        '--specpath',
        str(tmpdir),
        '--distpath',
        str(tmpdir.join("dist")),
        '--workpath',
        str(tmpdir.join("build")),
        '--path',
        str(tmpdir),
    ]

    pyi_args = [script] + default_args
    PYI_CONFIG = configure.get_config(upx_dir=None)
    PYI_CONFIG['cachedir'] = str(tmpdir)

    with pytest.raises(SystemExit) as execinfo:
        pyi_main.run(pyi_args, PYI_CONFIG)
    assert "sys.setrecursionlimit" in str(execinfo.value)
コード例 #8
0
ファイル: qcompiler.py プロジェクト: Qboi123/QPythonCompiler
    def compile(self, command):
        """
        Compile the workspace, with the given command for PyInstaller
        :param command:
        :return:
        """
        from PyInstaller import __main__ as pyi

        # Initialize variables
        temporary_directory = self.join_path(self.mainFolder, "obj")
        output = self.join_path(self.mainFolder, "bin")

        # Notify the user of the workspace and setup building to it
        print("Building in the current instances temporary directory at {}".format(temporary_directory))
        print("To get a new temporary directory, restart this application")
        dist_path = os.path.join(temporary_directory, 'application')
        build_path = os.path.join(temporary_directory, 'build')
        extra_args = ['--distpath', dist_path] + ['--workpath', build_path] + ['--specpath', temporary_directory]

        # Run PyInstaller
        sys.argv = shlex.split(command) + extra_args  # Put command into sys.argv and extra args
        print("Executing: {0}".format(command))
        pyi.run()  # Execute PyInstaller
        print("An error occurred, traceback follows:", file=sys.stderr)
        print(traceback.format_exc(), file=sys.stderr)

        # Move project if there was no failure
        output_directory = os.path.abspath(output)  # Use absolute directories
        print("Moving project to: {0}".format(output_directory))
        self.move_project(dist_path, output_directory)
        print("Complete.")
コード例 #9
0
def test_widgets(tmp_path) -> NoReturn:
    """Test that all widgets are accesible."""

    app_name = "userapp"
    workpath = tmp_path / "build"
    distpath = tmp_path / "dist"
    app = tmp_path / (app_name + ".py")
    app.write_text(
        """
import os

import kivymd  # NOQA
__import__("kivymd.uix.label")
__import__("kivymd.uix.button")
__import__("kivymd.uix.list")
__import__("kivymd.uix.navigationdrawer")

print(os.listdir(os.path.dirname(kivymd.uix.__path__[0])))
"""
    )
    pyi_main.run(
        [
            "--workpath",
            str(workpath),
            "--distpath",
            str(distpath),
            "--specpath",
            str(tmp_path),
            str(app),
        ]
    )
    subprocess.run([str(distpath / app_name / app_name)], check=True)
コード例 #10
0
    def _test_building(self, args):
        """
        Run building of test script.

        :param args: additional CLI options for PyInstaller.

        Return True if build succeded False otherwise.
        """
        default_args = [
            '--debug=bootloader',
            '--noupx',
            '--specpath', self._specdir,
            '--distpath', self._distdir,
            '--workpath', self._builddir,
            '--path', _get_modules_dir(self._request),
            '--log-level=INFO',
        ]   # yapf: disable

        # Choose bundle mode.
        if self._mode == 'onedir':
            default_args.append('--onedir')
        elif self._mode == 'onefile':
            default_args.append('--onefile')
        # if self._mode is None then just the spec file was supplied.

        pyi_args = [self.script] + default_args + args
        # TODO: fix return code in running PyInstaller programatically.
        PYI_CONFIG = configure.get_config(upx_dir=None)
        # Override CACHEDIR for PyInstaller and put it into self.tmpdir
        PYI_CONFIG['cachedir'] = str(self._tmpdir)

        pyi_main.run(pyi_args, PYI_CONFIG)
        retcode = 0

        return retcode == 0
コード例 #11
0
    def _test_building(self, args):
        """
        Run building of test script.

        :param args: additional CLI options for PyInstaller.

        Return True if build succeded False otherwise.
        """
        default_args = [
            '--debug=bootloader', '--noupx', '--specpath', self._specdir,
            '--distpath', self._distdir, '--workpath', self._builddir,
            '--path', _MODULES_DIR, '--log-level=DEBUG'
        ]

        # Choose bundle mode.
        if self._mode == 'onedir':
            default_args.append('--onedir')
        elif self._mode == 'onefile':
            default_args.append('--onefile')
        # if self._mode is None then just the spec file was supplied.

        pyi_args = [self.script] + default_args + args
        # TODO fix return code in running PyInstaller programatically
        PYI_CONFIG = configure.get_config(upx_dir=None)
        # Override CACHEDIR for PyInstaller and put it into self.tmpdir
        PYI_CONFIG['cachedir'] = self._tmpdir
        # Speed up tests by reusing copy of basic module graph object.
        PYI_CONFIG['tests_modgraph'] = copy.deepcopy(self._modgraph)

        pyi_main.run(pyi_args, PYI_CONFIG)
        retcode = 0

        return retcode == 0
コード例 #12
0
ファイル: build.py プロジェクト: staffzzz/grr
    def BuildWithPyInstaller(self):
        """Use pyinstaller to build a client package."""
        self.CleanDirectory(
            config_lib.CONFIG.Get("PyInstaller.distpath",
                                  context=self.context))

        logging.info("Copying pyinstaller support files")
        self.spec_file = os.path.join(self.build_dir, "grr.spec")

        with open(self.spec_file, "wb") as fd:
            fd.write(
                config_lib.CONFIG.Get("PyInstaller.spec",
                                      context=self.context))

        with open(os.path.join(self.build_dir, "version.txt"), "wb") as fd:
            fd.write(
                config_lib.CONFIG.Get("PyInstaller.version",
                                      context=self.context))

        with open(os.path.join(self.build_dir, "grr.ico"), "wb") as fd:
            fd.write(
                config_lib.CONFIG.Get("PyInstaller.icon",
                                      context=self.context))

        # We expect the onedir output at this location.
        self.output_dir = os.path.join(
            config_lib.CONFIG.Get("PyInstaller.distpath",
                                  context=self.context), "grr-client")

        # Pyinstaller doesn't handle unicode strings.
        args = [
            "--distpath",
            str(
                config_lib.CONFIG.Get("PyInstaller.distpath",
                                      context=self.context)), "--workpath",
            str(
                config_lib.CONFIG.Get("PyInstaller.workpath_dir",
                                      context=self.context)),
            str(self.spec_file)
        ]
        logging.info("Running pyinstaller: %s", args)
        PyInstallerMain.run(pyi_args=[utils.SmartStr(x) for x in args])

        # Clear out some crud that pyinstaller includes.
        for path in ["tcl", "tk", "pytz"]:
            dir_path = os.path.join(self.output_dir, path)
            try:
                shutil.rmtree(dir_path)
                os.mkdir(dir_path)
                # Create an empty file so the directories get put in the installers.
                with open(os.path.join(dir_path, path), "wb"):
                    pass
            except OSError:
                pass

        with open(os.path.join(self.output_dir, "build.yaml"), "w") as fd:
            fd.write("Client.build_environment: %s\n" %
                     rdf_client.Uname.FromCurrentSystem().signature())
            fd.write("Client.build_time: '%s'\n" %
                     str(rdfvalue.RDFDatetime().Now()))
コード例 #13
0
    def BuildWithPyInstaller(self):
        """Use pyinstaller to build a client package."""
        self.CleanDirectory(
            config.CONFIG.Get("PyInstaller.distpath", context=self.context))

        logging.info("Copying pyinstaller support files")
        self.spec_file = os.path.join(self.build_dir, "grr.spec")

        with open(self.spec_file, "wb") as fd:
            fd.write(
                config.CONFIG.Get("PyInstaller.spec", context=self.context))

        with open(os.path.join(self.build_dir, "version.txt"), "wb") as fd:
            fd.write(
                config.CONFIG.Get("PyInstaller.version", context=self.context))

        with open(os.path.join(self.build_dir, "grr.ico"), "wb") as fd:
            fd.write(
                config.CONFIG.Get("PyInstaller.icon", context=self.context))

        # We expect the onedir output at this location.
        self.output_dir = os.path.join(
            config.CONFIG.Get("PyInstaller.distpath", context=self.context),
            "grr-client")

        # Pyinstaller doesn't handle unicode strings.
        args = [
            "--distpath",
            str(config.CONFIG.Get("PyInstaller.distpath",
                                  context=self.context)), "--workpath",
            str(
                config.CONFIG.Get("PyInstaller.workpath_dir",
                                  context=self.context)),
            str(self.spec_file)
        ]
        logging.info("Running pyinstaller: %s", args)
        PyInstallerMain.run(pyi_args=[utils.SmartStr(x) for x in args])

        # Clear out some crud that pyinstaller includes.
        for path in ["tcl", "tk", "pytz"]:
            dir_path = os.path.join(self.output_dir, path)
            try:
                shutil.rmtree(dir_path)
                os.mkdir(dir_path)
                # Create an empty file so the directories get put in the installers.
                with open(os.path.join(dir_path, path), "wb"):
                    pass
            except OSError:
                pass

        version_ini = config_lib.Resource().Filter("version.ini")
        if not os.path.exists(version_ini):
            raise RuntimeError(
                "Couldn't find version_ini in virtual env root: %s" %
                version_ini)
        shutil.copy(version_ini, os.path.join(self.output_dir, "version.ini"))

        with open(os.path.join(self.output_dir, "build.yaml"), "wb") as fd:
            self.WriteBuildYaml(fd)
コード例 #14
0
ファイル: setup.py プロジェクト: Ppasha9/DiplomaApps
def setup(opts):
    if opts.get('--fid-calculator-exe', None):
        run([
            '--name=FID_Calculator',
            '--onefile',
            '--console',
            'main_fid_calculator.py',
        ])
コード例 #15
0
ファイル: runtests.py プロジェクト: jack-liaojie/LED_DEMO
    def test_building(self):
        """
        Run building of test script.

        Return True if build succeded False otherwise.
        """
        OPTS = [
            '--debug', '--noupx', '--specpath', self._specdir, '--distpath',
            self._distdir, '--workpath', self._builddir
        ]

        if self.verbose:
            OPTS.extend(['--debug', '--log-level=INFO'])
        else:
            OPTS.append('--log-level=ERROR')

        # Build executable in onefile mode.
        if self.test_file.startswith('test_onefile'):
            OPTS.append('--onefile')
        else:
            OPTS.append('--onedir')

        if self.with_crypto or '_crypto' in self.test_file:
            print('NOTE: Bytecode encryption is enabled for this test.',
                  end="")
            OPTS.append('--key=test_key')

        self._msg("BUILDING TEST " + self.test_name)

        # Use pyinstaller.py for building test_name.
        testfile_spec = self.test_file + '.spec'
        if not os.path.exists(self.test_file + '.spec'):
            # .spec file does not exist and it has to be generated
            # for main script.
            testfile_spec = self.test_file + '.py'

        #pyinst_script = os.path.join(HOMEPATH, 'pyinstaller.py')

        # TODO Fix redirecting stdout/stderr
        # In report mode is stdout and sys.stderr redirected.
        #if self.report:
        ## Write output from subprocess to stdout/err.
        #retcode, out, err = compat.exec_python_all(pyinst_script,
        #testfile_spec, *OPTS)
        #sys.stdout.write(out)
        #sys.stdout.write(err)
        #else:
        #retcode = compat.exec_python_rc(pyinst_script,
        #testfile_spec, *OPTS)
        # abspath is required due to makespec.make_path_spec_relative()
        testfile_spec = os.path.abspath(testfile_spec)
        pyi_args = [testfile_spec] + OPTS
        # TODO fix return code in running PyInstaller programatically
        pyi_main.run(pyi_args, PYI_CONFIG)
        retcode = 0

        return retcode == 0
コード例 #16
0
ファイル: runtests.py プロジェクト: pyinstaller/pyinstaller
    def test_building(self):
        """
        Run building of test script.

        Return True if build succeded False otherwise.
        """
        OPTS = ['--debug', '--noupx',
                '--specpath', self._specdir,
                '--distpath', self._distdir,
                '--workpath', self._builddir]

        if self.verbose:
            OPTS.extend(['--debug', '--log-level=INFO'])
        else:
            OPTS.append('--log-level=ERROR')

        # Build executable in onefile mode.
        if self.test_file.startswith('test_onefile'):
            OPTS.append('--onefile')
        else:
            OPTS.append('--onedir')

        if self.with_crypto or '_crypto' in self.test_file:
            print('NOTE: Bytecode encryption is enabled for this test.', end="")
            OPTS.append('--key=test_key')

        self._msg("BUILDING TEST " + self.test_name)

        # Use pyinstaller.py for building test_name.
        testfile_spec = self.test_file + '.spec'
        if not os.path.exists(self.test_file + '.spec'):
            # .spec file does not exist and it has to be generated
            # for main script.
            testfile_spec = self.test_file + '.py'

        #pyinst_script = os.path.join(HOMEPATH, 'pyinstaller.py')

        # TODO Fix redirecting stdout/stderr
        # In report mode is stdout and sys.stderr redirected.
        #if self.report:
            ## Write output from subprocess to stdout/err.
            #retcode, out, err = compat.exec_python_all(pyinst_script,
                  #testfile_spec, *OPTS)
            #sys.stdout.write(out)
            #sys.stdout.write(err)
        #else:
            #retcode = compat.exec_python_rc(pyinst_script,
                  #testfile_spec, *OPTS)
        # abspath is required due to makespec.make_path_spec_relative()
        testfile_spec = os.path.abspath(testfile_spec)
        pyi_args = [testfile_spec] + OPTS
        # TODO fix return code in running PyInstaller programatically
        pyi_main.run(pyi_args, PYI_CONFIG)
        retcode = 0

        return retcode == 0
コード例 #17
0
def __main__():
    if len(sys.argv) < 2:
        print("Need more arguments: Usage: python_build_template.py [starter_script]")
        return 
    packages_location = get_python_lib()
    all_modules = get_possible_modules(packages_location)
    entry_file = sys.argv[1]
    # Creates a list of hidden imports arguments for pyinstaller in the format - "--hidden-import=<module>"
    hidden_modules_commands = ["--hidden-import=" + module_name for module_name in all_modules]
    run(["--paths=" + packages_location, "--distpath=.", *hidden_modules_commands, "--name=worker-bundle", entry_file])
コード例 #18
0
    def compile_file(self, path):
        path = os.path.abspath(path)

        build_path = os.path.join(self.tmp_dir, 'build')
        cmd = 'pyinstaller -y -F -w {}'.format(shlex.quote(path))

        sys.argv = shlex.split(cmd) + ['--distpath', self.dist_path] + \
            ['--workpath', build_path] + ['--specpath', self.tmp_dir]

        pyi.run()
コード例 #19
0
def openUI():
    opts = [
        'MPlayer.py', '--noconsole',
        '--distpath=%s' % os.path.join(file_path, 'dist').replace('\\', '/'),
        '--workpath=%s' % os.path.join(file_path, 'build').replace('\\', '/'),
        '--specpath=%s' % os.path.dirname(__file__), '-y', '--clean',
        '--icon=%s' % os.path.join(
            file_path, 'source/UI/icons/exe_icon.ico').replace('\\', '/')
    ]
    run(opts)
コード例 #20
0
ファイル: build.py プロジェクト: destijl/grr
  def BuildWithPyInstaller(self):
    """Use pyinstaller to build a client package."""
    self.CleanDirectory(
        config_lib.CONFIG.Get("PyInstaller.distpath", context=self.context))

    logging.info("Copying pyinstaller support files")
    self.spec_file = os.path.join(self.build_dir, "grr.spec")

    with open(self.spec_file, "wb") as fd:
      fd.write(config_lib.CONFIG.Get("PyInstaller.spec", context=self.context))

    with open(os.path.join(self.build_dir, "version.txt"), "wb") as fd:
      fd.write(
          config_lib.CONFIG.Get("PyInstaller.version", context=self.context))

    with open(os.path.join(self.build_dir, "grr.ico"), "wb") as fd:
      fd.write(config_lib.CONFIG.Get("PyInstaller.icon", context=self.context))

    # We expect the onedir output at this location.
    self.output_dir = os.path.join(
        config_lib.CONFIG.Get("PyInstaller.distpath", context=self.context),
        "grr-client")

    # Pyinstaller doesn't handle unicode strings.
    args = [
        "--distpath", str(
            config_lib.CONFIG.Get("PyInstaller.distpath",
                                  context=self.context)), "--workpath",
        str(
            config_lib.CONFIG.Get("PyInstaller.workpath_dir",
                                  context=self.context)), str(self.spec_file)
    ]
    logging.info("Running pyinstaller: %s", args)
    PyInstallerMain.run(pyi_args=[utils.SmartStr(x) for x in args])

    # Clear out some crud that pyinstaller includes.
    for path in ["tcl", "tk", "pytz"]:
      dir_path = os.path.join(self.output_dir, path)
      try:
        shutil.rmtree(dir_path)
        os.mkdir(dir_path)
        # Create an empty file so the directories get put in the installers.
        with open(os.path.join(dir_path, path), "wb"):
          pass
      except OSError:
        pass

    version_ini = config_lib.Resource().Filter("version.ini")
    if not os.path.exists(version_ini):
      raise RuntimeError("Couldn't find version_ini in virtual env root: %s" %
                         version_ini)
    shutil.copy(version_ini, os.path.join(self.output_dir, "version.ini"))

    with open(os.path.join(self.output_dir, "build.yaml"), "wb") as fd:
      self.WriteBuildYaml(fd)
コード例 #21
0
def convert(command, output, disable_recursion_limit):
    """ Package the executable passing the arguments the user requested """
    eel.addOutput("Running auto-py-to-exe v" + version)
    # Notify the user of the workspace and setup building to it
    eel.addOutput(
        "Building in the current instances temporary directory at {}\n".format(
            temporary_directory))
    eel.addOutput(
        "To get a new temporary directory, restart this application\n")
    dist_path = os.path.join(temporary_directory, 'application')
    build_path = os.path.join(temporary_directory, 'build')
    extra_args = ['--distpath', dist_path] + ['--workpath', build_path] + [
        '--specpath', temporary_directory
    ]

    # If the Recursion Limit is enabled, set it
    if not disable_recursion_limit:
        sys.setrecursionlimit(5000)
        eel.addOutput("Recursion Limit is set to 5000\n")
    else:
        sys.setrecursionlimit(
            DEFAULT_RECURSION_LIMIT
        )  # In the case the limit was set and now the user doesn't want it set

    # Run PyInstaller
    pyinstaller_fail = True
    cs.start()  # Capture stderr so PyInstaller output can be send to UI
    sys.argv = shlex.split(
        command) + extra_args  # Put command into sys.argv and extra args
    try:
        eel.addOutput("Executing: {0}\n".format(command))
        pyi.run()  # Execute PyInstaller
        pyinstaller_fail = False
    except:
        eel.addOutput("An error occurred, traceback follows:\n")
        eel.addOutput(traceback.format_exc())
    cs.stop()  # Stop stderr capture

    # Move project if there was no failure
    if pyinstaller_fail:
        eel.addOutput("\n")
        eel.addOutput("Project output will not be moved to output folder\n")
    else:
        output_directory = os.path.abspath(output)  # Use absolute directories
        eel.addOutput("Moving project to: {0}\n".format(output_directory))
        try:
            move_project(dist_path, output_directory)
        except:
            eel.addOutput("Failed to move project, traceback follows:\n")
            eel.addOutput(traceback.format_exc())

    eel.addOutput("Complete.\n")
    eel.outputComplete()
コード例 #22
0
def main():
    print('Building installation directory')
    sys.argv = ['pyinstaller', 'flamenco-worker.spec', '--log-level', 'WARN']
    run()

    prefix = 'flamenco-worker-%s' % __version__
    dist_dir = Path('dist').absolute()

    print('Creating archive')
    if platform.system().lower() == 'windows':
        create_zip(prefix, dist_dir)
    else:
        create_tar(prefix, dist_dir)
コード例 #23
0
ファイル: build.py プロジェクト: Dev-Tech-Studio/grr
  def BuildWithPyInstaller(self):
    """Use pyinstaller to build a client package."""
    self.CleanDirectory(config_lib.CONFIG.Get("PyInstaller.distpath",
                                              context=self.context))

    logging.info("Copying pyinstaller support files")
    self.spec_file = os.path.join(self.build_dir, "grr.spec")

    with open(self.spec_file, "wb") as fd:
      fd.write(config_lib.CONFIG.Get("PyInstaller.spec", context=self.context))

    with open(os.path.join(self.build_dir, "version.txt"), "wb") as fd:
      fd.write(config_lib.CONFIG.Get("PyInstaller.version",
                                     context=self.context))

    with open(os.path.join(self.build_dir, "grr.ico"), "wb") as fd:
      fd.write(config_lib.CONFIG.Get("PyInstaller.icon", context=self.context))

    # We expect the onedir output at this location.
    self.output_dir = os.path.join(
        config_lib.CONFIG.Get("PyInstaller.distpath", context=self.context),
        "grr-client")

    # Pyinstaller doesn't handle unicode strings.
    args = ["--distpath", str(config_lib.CONFIG.Get("PyInstaller.distpath",
                                                    context=self.context)),
            "--workpath", str(config_lib.CONFIG.Get("PyInstaller.workpath_dir",
                                                    context=self.context)),
            str(self.spec_file)]
    logging.info("Running pyinstaller: %s", args)
    PyInstallerMain.run(pyi_args=[utils.SmartStr(x) for x in args])

    # Clear out some crud that pyinstaller includes.
    for path in ["tcl", "tk", "pytz"]:
      dir_path = os.path.join(self.output_dir, path)
      try:
        shutil.rmtree(dir_path)
        os.mkdir(dir_path)
        # Create an empty file so the directories get put in the installers.
        with open(os.path.join(dir_path, path), "wb"):
          pass
      except OSError:
        pass

    with open(os.path.join(self.output_dir, "build.yaml"), "w") as fd:
      fd.write("Client.build_environment: %s\n" %
               rdf_client.Uname.FromCurrentSystem().signature())
      fd.write("Client.build_time: '%s'\n" %
               str(rdfvalue.RDFDatetime().Now()))
コード例 #24
0
    def run(self):
        # install code
        pip_main(['install', '.'])

        specs = self.distribution.pyinstaller_specs

        print("specs: {}".format(specs))

        for spec in specs:
            pyi_args = [
                "--noconfirm", "--onefile", "--distpath=.", "--clean",
                os.path.join(PATH, spec)]

            with remember_cwd(EXE_BUILD_DIR):
                run(pyi_args)
コード例 #25
0
def test_pyinstaller_hook(tmp_path):
    appfile = tmp_path / "sample.py"
    appfile.write_text("""\
import globus_sdk
ac = globus_sdk.AuthClient()
""")
    pyi_main.run([
        "--workpath",
        str(tmp_path / "build"),
        "--distpath",
        str(tmp_path / "dist"),
        "--specpath",
        str(tmp_path),
        str(appfile),
    ])
    subprocess.run([str(tmp_path / "dist" / "sample" / "sample")], check=True)
コード例 #26
0
def build_sscanss():
    """Builds the executable for the sscanss application"""
    work_path = INSTALLER_PATH / 'temp'
    dist_path = INSTALLER_PATH / 'bundle' / 'app'
    main_path = PROJECT_PATH / 'sscanss' / 'app' / 'main.py'
    shutil.rmtree(dist_path, ignore_errors=True)

    pyi_args = [
        '--name', 'sscanss', '--specpath',
        str(work_path), '--workpath',
        str(work_path), '--windowed', '--noconfirm', '--distpath',
        str(dist_path), '--clean',
        str(main_path)
    ]

    pyi_args.extend([
        '--exclude-module', 'PyQt5.Qsci', '--hidden-import',
        'PyQt5.QtPrintSupport', *EXCLUDED_IMPORT, *HIDDEN_IMPORT
    ])

    if IS_WINDOWS:
        pyi_args.extend(['--icon', str(INSTALLER_PATH / 'icons' / 'logo.ico')])

    pyi.run(pyi_args)

    exec_folder = next(dist_path.iterdir())
    exec_folder.rename(dist_path / 'bin')
    shutil.rmtree(work_path)

    # Copy resources into installer directory
    resources = ['instruments', 'static', 'LICENSE']

    for resource in resources:
        dest_path = dist_path / resource
        src_path = PROJECT_PATH / resource
        if src_path.is_file():
            shutil.copy(src_path, dest_path)
        else:
            shutil.copytree(src_path,
                            dest_path,
                            ignore=shutil.ignore_patterns('__pycache__'))

    if IS_WINDOWS:
        with open(INSTALLER_PATH / 'windows' / 'version.nsh', 'w') as ver_file:
            from sscanss.__version import __version__

            ver_file.write(f'!define VERSION "{__version__}"')
コード例 #27
0
def build_sscanss():
    """Builds the executable for the sscanss application"""
    work_path = os.path.join(INSTALLER_PATH, 'temp')
    dist_path = os.path.join(INSTALLER_PATH, 'bundle', 'app')
    main_path = os.path.join(PROJECT_PATH, 'sscanss', 'app', 'main.py')
    shutil.rmtree(dist_path, ignore_errors=True)

    pyi_args = [
        '--name', 'sscanss', '--specpath', work_path, '--workpath', work_path,
        '--windowed', '--noconfirm', '--distpath', dist_path, '--clean',
        main_path
    ]

    pyi_args.extend([
        '--exclude-module', 'PyQt5.Qsci', '--hidden-import',
        'PyQt5.QtPrintSupport', *EXCLUDED_IMPORT, *HIDDEN_IMPORT
    ])

    if IS_WINDOWS:
        pyi_args.extend(
            ['--icon',
             os.path.join(INSTALLER_PATH, 'icons', 'logo.ico')])

    pyi.run(pyi_args)

    exe_folder = os.listdir(dist_path)[0]
    os.rename(os.path.join(dist_path, exe_folder),
              os.path.join(dist_path, 'bin'))
    shutil.rmtree(work_path)

    # Copy resources into installer directory
    resources = ['instruments', 'static', 'LICENSE']

    for resource in resources:
        dest_path = os.path.join(dist_path, resource)
        src_path = os.path.join(PROJECT_PATH, resource)
        if os.path.isfile(src_path):
            shutil.copy(src_path, dest_path)
        else:
            shutil.copytree(src_path,
                            dest_path,
                            ignore=shutil.ignore_patterns('__pycache__'))

    if IS_WINDOWS:
        with open(os.path.join(INSTALLER_PATH, 'windows', 'version.nsh'),
                  'w') as ver_file:
            ver_file.write(f'!define VERSION "{__version__}"')
コード例 #28
0
def convert(command, output):
    """ Package the executable passing the arguments the user requested """
    # Initially clean the workspace
    eel.addOutput("Cleaning workspace\n")
    try:
        clean()
    except:
        eel.addOutput(
            "Warning: could not clean the workspace before starting\n")

    # Run PyInstaller
    pyinstaller_fail = True
    cs.start()  # Capture stderr so PyInstaller output can be send to UI
    sys.argv = shlex.split(command)  # Put command into sys.argv
    try:
        pyi.run()  # Execute PyInstaller
        pyinstaller_fail = False
    except:
        eel.addOutput("An error occurred, traceback follows:\n")
        eel.addOutput(traceback.format_exc())
    cs.stop()  # Stop stderr capture

    # Move Project
    if pyinstaller_fail:
        eel.addOutput("\n")
        eel.addOutput("Project output will not be moved to output folder\n")
    else:
        eel.addOutput("Moving project to: " + output + "\n")
        try:
            moveProject(output)
        except:
            eel.addOutput("Failed to move project, traceback follows:\n")
            eel.addOutput(traceback.format_exc())

    # Clean the workspace
    eel.addOutput("Cleaning workspace\n")
    try:
        clean()
    except:
        eel.addOutput(
            "Warning: could not clean the workspace; some build files will still exist\n"
        )

    eel.addOutput("Complete.\n")
    eel.outputComplete()
コード例 #29
0
def test_pyi_hooksample(tmp_path):
    app_name = "userapp"
    workpath = tmp_path / "build"
    distpath = tmp_path / "dist"
    app = tmp_path / (app_name + ".py")
    app.write_text("\n".join(["import usb1", "print(usb1.getVersion())"]))
    args = [
        # Place all generated files in ``tmp_path``.
        '--workpath',
        str(workpath),
        '--distpath',
        str(distpath),
        '--specpath',
        str(tmp_path),
        str(app),
    ]
    pyi_main.run(args)
    subprocess.run([str(distpath / app_name / app_name)], check=True)
コード例 #30
0
def _generate_executable():
    current_dir = os.getcwd()
    client_file = os.path.join(current_dir, 'src/client.py')
    distdir = os.path.join(current_dir, 'dist')
    builddir = os.path.join(current_dir, 'build')

    if not os.path.exists('dist'):
        os.makedirs('dist')
    if not os.path.exists('build'):
        os.makedirs('build')
    executable_generator.run([
        client_file,
        '--onefile',
        '--distpath',
        distdir,
        '--workpath',
        builddir,
    ])
コード例 #31
0
def convert(command, output):
    eel.addOutput("Cleaning file structure\n")
    clean()

    cs.start()  # Capture stderr so PyInstaller output can be send to UI
    sys.argv = shlex.split(command)  # Put command into sys.argv
    pyi.run()  # Execute PyInstaller
    cs.stop()  # Stop stderr capture

    eel.addOutput("Moving project to: " + output + "\n")
    try:
        moveProject(output)
    except:
        eel.addOutput("Failed to move project. Did an error occur?\n")
    eel.addOutput("Cleaning file structure\n")
    clean()
    eel.addOutput("Complete.\n")
    eel.outputComplete()
コード例 #32
0
def test_pyinstaller_scoutsuite(tmp_path):
    app_name = "ScoutSuiteApp"
    workpath = tmp_path / "build"
    distpath = tmp_path / "dist"
    app = tmp_path / (app_name + ".py")
    app.write_text("\n".join(TEST_CODE))
    args = [
        # Place all generated files in ``tmp_path``.
        '--workpath',
        str(workpath),
        '--distpath',
        str(distpath),
        '--specpath',
        str(tmp_path),
        '--clean',
        str(app),
    ]
    pyi_main.run(args)
    subprocess.run([str(distpath / app_name / app_name)], check=True)
コード例 #33
0
def build(path, inConsole=False, addWeb=False):
    params = [path, "--noupx", "--onefile"]

    if not inConsole:
        params.append("--noconsole")

    web = os.path.join(os.path.dirname(path), "web")
    if addWeb and os.path.isdir(web):
        sep = (os.name == 'nt') and ";" or ":"
        params.append("--add-data=%s%sweb" % (web, sep))

    temp = os.path.join(tempfile.gettempdir(), ".build")
    params.append("--workpath")
    params.append(temp)

    params.append("--distpath")
    params.append(os.path.dirname(path))

    print("PYINSTALLER:", params)
    pyi.run(params)
コード例 #34
0
def build_editor():
    """Builds the executable for the instrument editor"""
    work_path = os.path.join(INSTALLER_PATH, 'temp')
    dist_path = os.path.join(INSTALLER_PATH, 'bundle')
    main_path = os.path.join(PROJECT_PATH, 'sscanss', 'editor', 'main.py')

    pyi_args = [
        '--name', 'editor', '--specpath', work_path, '--workpath', work_path,
        '--windowed', '--noconfirm', '--distpath', dist_path, '--clean',
        main_path
    ]

    pyi_args.extend([
        '--exclude-module', 'matplotlib', '--exclude-module', 'hdf5',
        '--hidden-import', 'PyQt5.QtPrintSupport', *EXCLUDED_IMPORT,
        *HIDDEN_IMPORT
    ])

    pyi_args.extend(
        ['--icon',
         os.path.join(INSTALLER_PATH, 'icons', 'editor-logo.ico')])
    pyi.run(pyi_args)
    shutil.rmtree(work_path)
コード例 #35
0
ファイル: installer.py プロジェクト: zsmatlab/labelimg
#!/usr/bin/env python
# encoding: utf-8

# --------------------------------------------------------
# file: installer.py
# Copyright(c) 2017-2020 SeetaTech
# Written by Zhuang Liu
# 10:34
# --------------------------------------------------------

from PyInstaller.__main__ import run

# -F: pack to a single exe file
# -w: without console
# --path: dependencies
# --icon: icon
# --noupx: without upx zip
# --clean: clean temp files

if __name__ == '__main__':
    opts=['-F', '-w', '--paths=C:/ProgramData/Anaconda2/envs/labelimg-installer3.5/Lib/site-packages/PyQt5/',
          '--paths=C:/ProgramData/Anaconda2/envs/labelimg-installer3.5/Lib/site-packages/PyQt5/plugins/',
          '--paths=./libs', 'labelImg.py']

    run(opts)
コード例 #36
0
ファイル: __main__.py プロジェクト: brentvollebregt/Eel
from __future__ import print_function
import sys
import pkg_resources as pkg
import PyInstaller.__main__ as pyi
import os

args = sys.argv[1:]
main_script = args.pop(0)
web_folder = args.pop(0)

print("Building executable with main script '%s' and web folder '%s'...\n" %
      (main_script, web_folder))

eel_js_file = pkg.resource_filename('eel', 'eel.js')
js_file_arg = '%s%seel' % (eel_js_file, os.pathsep)
web_folder_arg = '%s%s%s' % (web_folder, os.pathsep, web_folder)

needed_args = ['--hidden-import', 'bottle_websocket',
               '--add-data', js_file_arg, '--add-data', web_folder_arg]
full_args = [main_script] + needed_args + args

print('Running:\npyinstaller', ' '.join(full_args), '\n')

pyi.run(full_args)
コード例 #37
0
    def run(self):
        build.run(self)

        from PyInstaller.__main__ import run
        run(['-F', 'entrypoint.py'])
コード例 #38
0
ファイル: pyinstaller.py プロジェクト: cbgp/diyabc
#! /usr/bin/env python
#-----------------------------------------------------------------------------
# Copyright (c) 2013, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------


"""
Main command-line interface to PyInstaller.
"""

if __name__ == '__main__':
    from PyInstaller.__main__ import run
    run()
コード例 #39
0
ファイル: build.py プロジェクト: google/grr
  def BuildWithPyInstaller(self):
    """Use pyinstaller to build a client package."""
    self.CleanDirectory(
        config.CONFIG.Get("PyInstaller.distpath", context=self.context))

    logging.info("Copying pyinstaller support files")
    self.spec_file = os.path.join(self.build_dir, "grr.spec")

    with open(self.spec_file, "wb") as fd:
      fd.write(config.CONFIG.Get("PyInstaller.spec", context=self.context))

    with open(os.path.join(self.build_dir, "version.txt"), "wb") as fd:
      fd.write(config.CONFIG.Get("PyInstaller.version", context=self.context))

    shutil.copy(
        src=config.CONFIG.Get("PyInstaller.icon_path", context=self.context),
        dst=os.path.join(self.build_dir, u"grr.ico"))

    # We expect the onedir output at this location.
    self.output_dir = os.path.join(
        config.CONFIG.Get("PyInstaller.distpath", context=self.context),
        "grr-client")

    # Pyinstaller doesn't handle unicode strings.
    args = [
        "--distpath",
        str(config.CONFIG.Get("PyInstaller.distpath", context=self.context)),
        "--workpath",
        str(
            config.CONFIG.Get("PyInstaller.workpath_dir",
                              context=self.context)),
        str(self.spec_file)
    ]
    logging.info("Running pyinstaller: %s", args)
    PyInstallerMain.run(pyi_args=[utils.SmartStr(x) for x in args])

    # Clear out some crud that pyinstaller includes.
    for path in ["tcl", "tk", "pytz"]:
      dir_path = os.path.join(self.output_dir, path)
      try:
        shutil.rmtree(dir_path)
      except OSError:
        logging.error("Unable to remove directory: %s", dir_path)

      try:
        os.mkdir(dir_path)
      except OSError:
        logging.error("Unable to create directory: %s", dir_path)

      file_path = os.path.join(dir_path, path)
      try:
        # Create an empty file so the directories get put in the installers.
        with open(file_path, "wb"):
          pass
      except IOError:
        logging.error("Unable to create file: %s", file_path)

    version_ini = version.VersionPath()
    shutil.copy(version_ini, os.path.join(self.output_dir, "version.ini"))

    with open(os.path.join(self.output_dir, "build.yaml"), "wb") as fd:
      self.WriteBuildYaml(fd)