Python stat.S_IEXEC Examples

The following are 30 code examples of stat.S_IEXEC(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module stat , or try the search function .
Example #1
Source File: githooks.py    From renku-python with Apache License 2.0 6 votes vote down vote up
def install(client, force):
    """Install Git hooks."""
    warning_messages = []
    for hook in HOOKS:
        hook_path = Path(get_hook_path(hook, client.repo.git_dir))
        if hook_path.exists():
            if not force:
                warning_messages.append(
                    'Hook already exists. Skipping {0}'.format(str(hook_path))
                )
                continue
            else:
                hook_path.unlink()

        # Make sure the hooks directory exists.
        hook_path.parent.mkdir(parents=True, exist_ok=True)

        Path(hook_path).write_bytes(
            pkg_resources.resource_string(
                'renku.data', '{hook}.sh'.format(hook=hook)
            )
        )
        hook_path.chmod(hook_path.stat().st_mode | stat.S_IEXEC)

    return warning_messages 
Example #2
Source File: bazelci.py    From continuous-integration with Apache License 2.0 6 votes vote down vote up
def download_bazel_binary_at_commit(dest_dir, platform, bazel_git_commit):
    bazel_binary_path = os.path.join(dest_dir, "bazel.exe" if platform == "windows" else "bazel")
    try:
        execute_command(
            [
                gsutil_command(),
                "cp",
                bazelci_builds_gs_url(platform, bazel_git_commit),
                bazel_binary_path,
            ]
        )
    except subprocess.CalledProcessError as e:
        raise BuildkiteException(
            "Failed to download Bazel binary at %s, error message:\n%s" % (bazel_git_commit, str(e))
        )
    st = os.stat(bazel_binary_path)
    os.chmod(bazel_binary_path, st.st_mode | stat.S_IEXEC)
    return bazel_binary_path 
Example #3
Source File: opengrm_ngram_binaries.py    From Montreal-Forced-Aligner with MIT License 6 votes vote down vote up
def collect_linux_binaries(directory):
    lib_dir = os.path.join(directory,'install', 'lib')
    bin_dir = os.path.join(directory,'install', 'bin')
    for name in os.listdir(bin_dir):
        ext = os.path.splitext(name)
        (key, value) = ext
        if value == exe_ext and key in included_filenames:
            out_path = os.path.join(bin_out, name)
            in_path = os.path.join(bin_dir, name)
            shutil.copyfile(in_path, out_path)
            st = os.stat(out_path)
            os.chmod(out_path, st.st_mode | stat.S_IEXEC)
    for name in os.listdir(lib_dir):
        if name in libraries:
            actual_lib = os.path.join(lib_dir, name)
            while os.path.islink(actual_lib):
                linkto = os.readlink(actual_lib)
                actual_lib = os.path.join(lib_dir, linkto)
            bin_name = os.path.join(bin_out, name)
            shutil.copyfile(actual_lib, bin_name) 
Example #4
Source File: zipapp.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def _copy_archive(archive, new_archive, interpreter=None):
    """Copy an application archive, modifying the shebang line."""
    with _maybe_open(archive, 'rb') as src:
        # Skip the shebang line from the source.
        # Read 2 bytes of the source and check if they are #!.
        first_2 = src.read(2)
        if first_2 == b'#!':
            # Discard the initial 2 bytes and the rest of the shebang line.
            first_2 = b''
            src.readline()

        with _maybe_open(new_archive, 'wb') as dst:
            _write_file_prefix(dst, interpreter)
            # If there was no shebang, "first_2" contains the first 2 bytes
            # of the source file, so write them before copying the rest
            # of the file.
            dst.write(first_2)
            shutil.copyfileobj(src, dst)

    if interpreter and isinstance(new_archive, str):
        os.chmod(new_archive, os.stat(new_archive).st_mode | stat.S_IEXEC) 
Example #5
Source File: download_chromedriver.py    From kboard with MIT License 6 votes vote down vote up
def download(version='LATEST'):
    destination_file_path = os.path.join(DESTINATION_DIR, MAC_DRIVER_NAME)
    destination_unzip_path = os.path.join(DESTINATION_DIR, 'chromedriver')
    if os.path.exists(destination_unzip_path):
        return "{} driver exists".format(destination_unzip_path)
    if version == 'LATEST':
        download_version = get_chromedriver_latest_version()
    else:
        download_version = version
    latest_path = "%s/%s/%s" % (DOWNLOAD_URL,
                                download_version, MAC_DRIVER_NAME)
    with open(destination_file_path, 'wb') as f:
        for chunk in requests.get(latest_path, stream=True).iter_content(chunk_size=1024):
            if chunk:
                f.write(chunk)
    with zipfile.ZipFile(destination_file_path, 'r') as f:
        with open(destination_unzip_path, 'wb') as d:
            d.write(f.read('chromedriver'))
    st = os.stat(destination_unzip_path)
    os.chmod(destination_unzip_path, (st.st_mode | stat.S_IEXEC))
    return destination_unzip_path 
Example #6
Source File: zipapp.py    From Imogen with MIT License 6 votes vote down vote up
def _copy_archive(archive, new_archive, interpreter=None):
    """Copy an application archive, modifying the shebang line."""
    with _maybe_open(archive, 'rb') as src:
        # Skip the shebang line from the source.
        # Read 2 bytes of the source and check if they are #!.
        first_2 = src.read(2)
        if first_2 == b'#!':
            # Discard the initial 2 bytes and the rest of the shebang line.
            first_2 = b''
            src.readline()

        with _maybe_open(new_archive, 'wb') as dst:
            _write_file_prefix(dst, interpreter)
            # If there was no shebang, "first_2" contains the first 2 bytes
            # of the source file, so write them before copying the rest
            # of the file.
            dst.write(first_2)
            shutil.copyfileobj(src, dst)

    if interpreter and isinstance(new_archive, str):
        os.chmod(new_archive, os.stat(new_archive).st_mode | stat.S_IEXEC) 
Example #7
Source File: setup.py    From eddy with GNU General Public License v3.0 6 votes vote down vote up
def make_linux(self):
        """
        Properly create a Linux executable.
        """
        if LINUX:
             path = os.path.join(self.build_exe, 'run.sh')
             with open(path, mode='w') as f:
                f.write(textwrap.dedent("""#!/bin/sh
                APP="{0}"
                EXEC="{1}"
                VERSION="{2}"
                DIRNAME=`dirname $0`
                LD_LIBRARY_PATH=$DIRNAME
                export LD_LIBRARY_PATH
                echo "Starting $APP $VERSION ..."
                chmod +x $DIRNAME/$EXEC
                $DIRNAME/$EXEC "$@"
                echo "... bye!"
                """.format(APPNAME, EXEC_NAME, VERSION)))

             for filename in [EXEC_NAME, 'run.sh']:
                 filepath = os.path.join(self.build_exe, filename)
                 st = os.stat(filepath)
                 os.chmod(filepath, st.st_mode | stat.S_IEXEC) 
Example #8
Source File: classdump.py    From Mobile-Security-Framework-MobSF with GNU General Public License v3.0 6 votes vote down vote up
def classdump_mac(clsdmp_bin, tools_dir, ipa_bin):
    """Run Classdump for Objective-C/Swift."""
    if clsdmp_bin == 'class-dump-swift':
        logger.info('Running class-dump-swift against binary')
        external = settings.CLASSDUMP_SWIFT_BINARY
    else:
        logger.info('Running class-dump against binary')
        external = settings.CLASSDUMP_BINARY
    if (len(external) > 0
            and is_file_exists(external)):
        class_dump_bin = external
    else:
        class_dump_bin = os.path.join(
            tools_dir, clsdmp_bin)
    # Execute permission check
    if not os.access(class_dump_bin, os.X_OK):
        os.chmod(class_dump_bin, stat.S_IEXEC)
    return subprocess.check_output([class_dump_bin, ipa_bin]) 
Example #9
Source File: conanfile.py    From conan-center-index with MIT License 6 votes vote down vote up
def _configure_autotools(self):
        if not self._autotools:
            self._autotools = AutoToolsBuildEnvironment(self, win_bash=tools.os_info.is_windows)
            if self.settings.os == "Macos":
                configure_file = "configure"
                tools.replace_in_file(configure_file, r"-install_name \$rpath/", "-install_name ")
                configure_stats = os.stat(configure_file)
                os.chmod(configure_file, configure_stats.st_mode | stat.S_IEXEC)
            configure_args = []
            if self.options.disable_assembly:
                configure_args.append('--disable-assembly')
            if self.options.shared:
                configure_args.extend(["--enable-shared", "--disable-static"])
            else:
                configure_args.extend(["--disable-shared", "--enable-static"])
            if self.options.enable_cxx:
                configure_args.append('--enable-cxx')
            self._autotools.configure(args=configure_args)
        return self._autotools 
Example #10
Source File: __init__.py    From Galaxy_Plugin_Bethesda with MIT License 5 votes vote down vote up
def create_exe(outpath, c_code=None):
    """Creates an executable file in the given location."""
    assert not os.path.exists(outpath), outpath
    if c_code:
        if not which("gcc"):
            raise ValueError("gcc is not installed")
        if isinstance(c_code, bool):        # c_code is True
            c_code = textwrap.dedent(
                """
                #include <unistd.h>
                int main() {
                    pause();
                    return 1;
                }
                """)
        assert isinstance(c_code, str), c_code
        with tempfile.NamedTemporaryFile(
                suffix='.c', delete=False, mode='wt') as f:
            f.write(c_code)
        try:
            subprocess.check_call(["gcc", f.name, "-o", outpath])
        finally:
            safe_rmpath(f.name)
    else:
        # copy python executable
        shutil.copyfile(PYTHON_EXE, outpath)
        if POSIX:
            st = os.stat(outpath)
            os.chmod(outpath, st.st_mode | stat.S_IEXEC) 
Example #11
Source File: sim.py    From pymanoid with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, sim, fname=None, tmp_folder='pymanoid_rec'):
        super(CameraRecorder, self).__init__()
        if fname is None:
            now = datetime.datetime.now()
            fname = now.strftime('pymanoid-%Y-%m-%d-%H%M%S.mp4')
        while tmp_folder.endswith('/'):
            tmp_folder = tmp_folder[:-1]
        sim.get_viewer_window_id()
        if not os.path.exists(tmp_folder):
            os.makedirs(tmp_folder)
        script_name = 'make_pymanoid_video.sh'
        with open(script_name, 'w') as script:
            frate = int(1. / sim.dt)
            script.write(
                ("#!/bin/sh\n") +
                (("avconv -r %d" % frate) +
                 (" -i %s/%%05d.png" % tmp_folder) +
                 (" -vf crop=\"trunc(iw/2)*2:trunc(ih/2)*2:0:0\"") +
                 (" %s" % fname)) +
                (" && rm -rf %s" % tmp_folder) +
                (" && rm %s" % script_name))
        st = fstat(script_name)
        chmod(script_name, st.st_mode | S_IEXEC)
        self.frame_index = 0
        self.sim = sim
        self.tmp_folder = tmp_folder 
Example #12
Source File: lift_program.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def make_executable(path):
  st = os.stat(path)
  os.chmod(path, st.st_mode | stat.S_IEXEC) 
Example #13
Source File: config.py    From hoverpy with Apache License 2.0 5 votes vote down vote up
def downloadHoverFly():
    tmp = tempfile.mkdtemp()
    bundlePath = join(tmp, "hoverfly_bundle_%s.zip" % dist)
    hoverflyBinTempFile = join(tmp, hoverflyBinFile)

    url = "https://github.com/SpectoLabs/hoverfly/"\
        "releases/download/v%s/hoverfly_bundle_%s.zip" % (
            dist_version, dist)

    print("DOWNLOADING HOVERFLY FROM %s TO %s" % (url, tmp))

    if sys.version_info.major == 2:
        import urllib
        urllib.urlretrieve(url, bundlePath)
    elif sys.version_info.major == 3:
        import shutil
        import urllib.request
        with urllib.request.urlopen(url) as response:
            with open(bundlePath, 'wb') as out_file:
                shutil.copyfileobj(response, out_file)

    print("UNZIPPING")
    zip_ref = zipfile.ZipFile(bundlePath, 'r')
    zip_ref.extractall(tmp)
    zip_ref.close()
    st = os.stat(hoverflyBinTempFile)
    os.chmod(hoverflyBinTempFile, st.st_mode | stat.S_IEXEC)
    return installHoverFly(hoverflyBinTempFile) 
Example #14
Source File: Runner.py    From PyMenu with GNU General Public License v3.0 5 votes vote down vote up
def runEmuMIPS(name, cmd, workdir, config, rom):
    name =  config["name"]
    cmd =  config["cmd"] if "cmd" in config else None
    workdir = config["workingDir"] if "workingDir" in config else None 
    overclock = config["overclock"] if "overclock" in config else None
    params = config["params"] if "params" in config else None

    if(workdir == None and not cmd == None):    
        workdir = os.path.abspath(os.path.join(cmd, os.pardir))

    fileName = "run"   
    file = open("/tmp/" + fileName,"w")
    file.write("#!/bin/sh\n")

    file.write("cd \"" + workdir + "\"\n")

    if(params != None):
        file.write(cmd + " " + params.replace("$f","\""+  rom + "\"") + "\n")
    else:
        file.write(cmd + " \"" + rom + "\"\n")     

    file.close() 
    
    st = os.stat('/tmp/' + fileName)
    os.chmod('/tmp/' + fileName, st.st_mode | stat.S_IEXEC)

    showLaunchImage()

    if(overclock != None and not Configuration.isOpenDinguX()):
        try:
           Overclock.setClock(overclock)
        except Exception as ex:
            pass
   
    TaskHandler.addPeriodicTask(0,  sys.exit , delay=100) 
Example #15
Source File: Runner.py    From PyMenu with GNU General Public License v3.0 5 votes vote down vote up
def runNativeMIPS(cmd, config):  
    cmd =  config["cmd"] if "cmd" in config else None
    screen = config["screen"] if "screen" in config else None  
    overclock = config["overclock"] if "overclock" in config else None
    selection = config["selection"] if "selection" in config else ""
    params = config["params"] if "params" in config else None


    fileName = "run"

    file = open("/tmp/" + fileName,"w")
    file.write("#!/bin/sh\n")
 
    parent = os.path.abspath(os.path.join(cmd, os.pardir))
    file.write("cd \"" + parent + "\"\n")

    if(params != None):
        file.write(cmd + " " + params.replace("$f","\""+  selection + "\"") + "\n")
    else:
        file.write("\"" + cmd  + "\" \"" + selection + "\"\n")     

  

    file.close() 
    st = os.stat('/tmp/' + fileName)
    os.chmod('/tmp/' + fileName, st.st_mode | stat.S_IEXEC)

    showLaunchImage()

    if(overclock != None):
        try:
            Overclock.setClock(overclock)
        except Exception as ex:
            pass
   
    TaskHandler.addPeriodicTask(0,  sys.exit , delay=100) 
Example #16
Source File: common.py    From scalyr-agent-2 with Apache License 2.0 5 votes vote down vote up
def _mock_python_binary_version(python_binary_name, version):
    # type: (six.text_type, six.text_type) -> None
    """
    Replace python binary with dummy srtipt that only print fake python version string.
    :return:
    """
    binary_path = BINARY_DIR_PATH / python_binary_name
    binary_path_backup_path = Path(six.text_type(binary_path) + "_bc")

    # this function was used previously delete old backup.
    if binary_path_backup_path.exists():
        shutil.copy(
            six.text_type(binary_path_backup_path), six.text_type(binary_path),
        )
        os.remove(six.text_type(binary_path_backup_path))

    if not version:
        os.system("python2 --version")
        return

    if not binary_path.exists():
        return

    # make backup of the original binary in case if we want to keep using it.
    shutil.copy(six.text_type(binary_path), six.text_type(binary_path_backup_path))
    os.remove(six.text_type(binary_path))

    # write new source to binary file. Now it just returns fake version.
    with binary_path.open("w") as f:
        f.write("#!/bin/bash\n")
        f.write("echo Python {0}\n".format(version))

    os.chmod(six.text_type(binary_path), stat.S_IWRITE | stat.S_IEXEC) 
Example #17
Source File: ExternalsDialog.py    From pychess with GNU General Public License v3.0 5 votes vote down vote up
def on_close_clicked(self, button):
        async def coro():
            altpath = getEngineDataPrefix()
            if pgn.scoutfish_path is None and conf.get("download_scoutfish"):
                binary = "https://github.com/pychess/scoutfish/releases/download/20170627/%s" % pgn.scoutfish
                filename = await download_file_async(binary)
                if filename is not None:
                    dest = shutil.move(filename, os.path.join(altpath, pgn.scoutfish))
                    os.chmod(dest, stat.S_IEXEC | stat.S_IREAD | stat.S_IWRITE)
                    pgn.scoutfish_path = dest

            if pgn.chess_db_path is None and conf.get("download_chess_db"):
                binary = "https://github.com/pychess/chess_db/releases/download/20170627/%s" % pgn.parser
                filename = await download_file_async(binary)
                if filename is not None:
                    dest = shutil.move(filename, os.path.join(altpath, pgn.parser))
                    os.chmod(dest, stat.S_IEXEC | stat.S_IREAD | stat.S_IWRITE)
                    pgn.chess_db_path = dest

            if TimeSeal.timestamp_path is None and conf.get("download_timestamp"):
                binary = "http://download.chessclub.com.s3.amazonaws.com/timestamp/%s" % TimeSeal.timestamp
                filename = await download_file_async(binary)
                if filename is not None:
                    dest = shutil.move(filename, os.path.join(altpath, TimeSeal.timestamp))
                    os.chmod(dest, stat.S_IEXEC | stat.S_IREAD | stat.S_IWRITE)
                    TimeSeal.timestamp_path = dest
        create_task(coro())

        self.window.emit("delete-event", None) 
Example #18
Source File: travis2docker.py    From travis2docker with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def chmod_execution(file_path):
        os.chmod(file_path, os.stat(file_path).st_mode | stat.S_IEXEC) 
Example #19
Source File: test_pydoc.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_apropos_empty_doc(self):
        pkgdir = os.path.join(TESTFN, 'walkpkg')
        os.mkdir(pkgdir)
        self.addCleanup(rmtree, pkgdir)
        init_path = os.path.join(pkgdir, '__init__.py')
        with open(init_path, 'w') as fobj:
            fobj.write("foo = 1")
        current_mode = stat.S_IMODE(os.stat(pkgdir).st_mode)
        try:
            os.chmod(pkgdir, current_mode & ~stat.S_IEXEC)
            with self.restrict_walk_packages(path=[TESTFN]), captured_stdout() as stdout:
                pydoc.apropos('')
            self.assertIn('walkpkg', stdout.getvalue())
        finally:
            os.chmod(pkgdir, current_mode) 
Example #20
Source File: populate.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def try_find(locations, basename):
    for p in locations:
        maybe = os.path.join(p, basename)
        if os.path.isfile(maybe):
            print(" > " + colors.green("Found " + maybe))
            new_file = os.path.join(bin_dir, basename)
            shutil.copyfile(maybe, new_file)
            st = os.stat(new_file)
            os.chmod(new_file, st.st_mode | stat.S_IEXEC)

            return True
    return False 
Example #21
Source File: filesystem.py    From RAFCON with Eclipse Public License 1.0 5 votes vote down vote up
def make_file_executable(filename):
    st = os.stat(filename)
    os.chmod(filename, st.st_mode | stat.S_IEXEC) 
Example #22
Source File: setup.py    From MAVSDK-Python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def download_mavsdk_server(self):
        print(
            f"downloading {self.mavsdk_server_url} into {self.mavsdk_server_filepath}")
        urllib.request.urlretrieve(
            self.mavsdk_server_url,
            filename=self.mavsdk_server_filepath)

        print(f"adding execution permission to {self.mavsdk_server_filepath}")
        st = os.stat(self.mavsdk_server_filepath)
        os.chmod(self.mavsdk_server_filepath, st.st_mode | stat.S_IEXEC) 
Example #23
Source File: converter.py    From Mobile-Security-Framework-MobSF with GNU General Public License v3.0 5 votes vote down vote up
def apk_2_java(app_path, app_dir, tools_dir):
    """Run jadx."""
    try:
        logger.info('APK -> JAVA')
        args = []
        output = os.path.join(app_dir, 'java_source/')
        logger.info('Decompiling to Java with jadx')

        if os.path.exists(output):
            shutil.rmtree(output)

        if (len(settings.JADX_BINARY) > 0
                and is_file_exists(settings.JADX_BINARY)):
            jadx = settings.JADX_BINARY
        elif platform.system() == 'Windows':
            jadx = os.path.join(tools_dir, 'jadx/bin/jadx.bat')
        else:
            jadx = os.path.join(tools_dir, 'jadx/bin/jadx')
        # Set execute permission, if JADX is not executable
        if not os.access(jadx, os.X_OK):
            os.chmod(jadx, stat.S_IEXEC)
        args = [
            jadx,
            '-ds',
            output,
            '-q',
            '-r',
            '--show-bad-code',
            app_path,
        ]
        fnull = open(os.devnull, 'w')
        subprocess.call(args,
                        stdout=fnull,
                        stderr=subprocess.STDOUT)
    except Exception:
        logger.exception('Decompiling to JAVA') 
Example #24
Source File: cloud_storage.py    From Jandroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _EnsureExecutable(gsutil):
  """chmod +x if gsutil is not executable."""
  st = os.stat(gsutil)
  if not st.st_mode & stat.S_IEXEC:
    os.chmod(gsutil, st.st_mode | stat.S_IEXEC) 
Example #25
Source File: cloud_storage.py    From Jandroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _EnsureExecutable(gsutil):
  """chmod +x if gsutil is not executable."""
  st = os.stat(gsutil)
  if not st.st_mode & stat.S_IEXEC:
    os.chmod(gsutil, st.st_mode | stat.S_IEXEC) 
Example #26
Source File: cloud_storage.py    From Jandroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _EnsureExecutable(gsutil):
  """chmod +x if gsutil is not executable."""
  st = os.stat(gsutil)
  if not st.st_mode & stat.S_IEXEC:
    os.chmod(gsutil, st.st_mode | stat.S_IEXEC) 
Example #27
Source File: utils.py    From plugin.audio.spotify with GNU General Public License v3.0 5 votes vote down vote up
def test_spotty(self, binary_path):
        '''self-test spotty binary'''
        try:
            st = os.stat(binary_path)
            os.chmod(binary_path, st.st_mode | stat.S_IEXEC)
            args = [
                binary_path,
                "-n", "selftest",
                "-x", "--disable-discovery"
            ]
            startupinfo = None
            if os.name == 'nt':
                startupinfo = subprocess.STARTUPINFO()
                startupinfo.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW
            spotty = subprocess.Popen(
                args,
                startupinfo=startupinfo,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                bufsize=0)
            stdout, stderr = spotty.communicate()
            log_msg(stdout)
            if "ok spotty" in stdout:
                return True
            elif xbmc.getCondVisibility("System.Platform.Windows"):
                log_msg("Unable to initialize spotty binary for playback."
                        "Make sure you have the VC++ 2015 runtime installed.", xbmc.LOGERROR)
        except Exception as exc:
            log_exception(__name__, exc)
        return False 
Example #28
Source File: utils.py    From PyPPL with Apache License 2.0 5 votes vote down vote up
def chmod_x(filepath):
    """@API
    Convert file1 to executable or add extract shebang to cmd line
    @params:
        filepath (path): The file path
    @returns:
        (list): with or without the path of the interpreter as the first element
        and the script file as the last element
    """
    from stat import S_IEXEC
    from os import chmod, stat
    filepath = str(filepath)
    if not fs.isfile(filepath):
        raise OSError('Unable to make {} as executable'.format(filepath))
    # in case it's a Path-like object
    ret = [filepath]
    try:
        chmod(filepath, stat(filepath).st_mode | S_IEXEC)
    except (OSError, PermissionError):
        shebang = None
        with open(filepath) as fsb:
            try:
                shebang = fsb.readline().strip()
            except (OSError, PermissionError, UnicodeDecodeError):
                # may raise UnicodeDecodeError for python3
                pass

        if not shebang or not shebang.startswith('#!'):
            raise OSError(
                'Unable to make {} as executable by chmod '
                'and detect interpreter from shebang.'.format(filepath))
        ret = shebang[2:].strip().split() + [filepath]
    return ret 
Example #29
Source File: utils.py    From plugin.audio.spotify with GNU General Public License v3.0 5 votes vote down vote up
def get_spotty_binary(self):
        '''find the correct spotty binary belonging to the platform'''
        sp_binary = None
        if xbmc.getCondVisibility("System.Platform.Windows"):
            sp_binary = os.path.join(os.path.dirname(__file__), "spotty", "windows", "spotty.exe")
        elif xbmc.getCondVisibility("System.Platform.OSX"):
            # macos binary is x86_64 intel
            sp_binary = os.path.join(os.path.dirname(__file__), "spotty", "darwin", "spotty")
        elif xbmc.getCondVisibility("System.Platform.Linux + !System.Platform.Android"):
            # try to find out the correct architecture by trial and error
            import platform
            architecture = platform.machine()
            log_msg("reported architecture: %s" % architecture)
            if architecture.startswith('AMD64') or architecture.startswith('x86_64'):
                # generic linux x86_64 binary
                sp_binary = os.path.join(os.path.dirname(__file__), "spotty", "x86-linux", "spotty-x86_64")
            else:
                # just try to get the correct binary path if we're unsure about the platform/cpu
                paths = []
##                paths.append(os.path.join(os.path.dirname(__file__), "spotty", "arm-linux", "spotty-muslhf"))
                paths.append(os.path.join(os.path.dirname(__file__), "spotty", "arm-linux", "spotty-hf"))
##                paths.append(os.path.join(os.path.dirname(__file__), "spotty", "arm-linux", "spotty"))
                paths.append(os.path.join(os.path.dirname(__file__), "spotty", "x86-linux", "spotty"))
                for binary_path in paths:
                    if self.test_spotty(binary_path):
                        sp_binary = binary_path
                        break
        if sp_binary:
            st = os.stat(sp_binary)
            os.chmod(sp_binary, st.st_mode | stat.S_IEXEC)
            log_msg("Architecture detected. Using spotty binary %s" % sp_binary)
        else:
            log_msg("Failed to detect architecture or platform not supported ! Local playback will not be available.")
        return sp_binary 
Example #30
Source File: test_zipapp.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_shebang_is_executable(self):
        # Test that an archive with a shebang line is made executable.
        source = self.tmpdir / 'source'
        source.mkdir()
        (source / '__main__.py').touch()
        target = self.tmpdir / 'source.pyz'
        zipapp.create_archive(str(source), str(target), interpreter='python')
        self.assertTrue(target.stat().st_mode & stat.S_IEXEC)